2017-02-21 84 views
1

我采取了ň字符串,然后我把它转换成BIGINTEGER之后,我将其存储到HashSet的但它显示运行时错误线程“main” java.lang.NumberFormatException 例外:零长度的BigInteger如何将字符串转换为bigInteger并存储在哈希集?

我的代码是:

import java.io.*; 
import java.util.*; 
import java.text.*; 
import java.math.*; 
import java.util.regex.*; 
class ex { 
    public static void main(String[] args) { 
     Scanner in = new Scanner(System.in); int n = in.nextInt();   
     HashSet<BigInteger> hs=new HashSet<BigInteger>(); 
     for(int i=0;i<n;i++) { 
       String str=in.nextLine(); 
       BigInteger bi=new BigInteger(str); 
       hs.add(bi); 
     } 
     Iterator itr=hs.iterator(); 
     while(itr.hasNext()) 
     System.out.println(itr.next()); 
    } 
} 
+0

SO不是一个留言板,你不应该试图解释你的问题在自己的意见(和*** ***肯定不尝试在那里添加代码)。相反,[编辑]你的问题,使其更好。 – azurefrog

回答

1

使用in.next()代替in.nextLine(),不要忘记关闭Scanner对象in

以下是完整main方法:

public static void main(String[] args) 
{ 
    Scanner in = new Scanner(System.in); 
    int n = in.nextInt(); 
    HashSet<BigInteger> hs = new HashSet<BigInteger>(); 
    for (int i = 0; i < n; i++) { 
     String str = in.next(); 
     BigInteger bi = new BigInteger(str); 
     hs.add(bi); 
    } 
    Iterator<BigInteger> itr = hs.iterator(); 
    while (itr.hasNext()) 
    System.out.println(itr.next()); 
    in.close(); 
} 
相关问题