gpt4 book ai didi

java - 如何将字符串转换为bigInteger并存储在哈希集中?

转载 作者:行者123 更新时间:2023-11-30 06:53:04 25 4
gpt4 key购买 nike

我取了n个字符串,然后将其转换为BIgInteger,然后将其存储到HashSet中,但它显示运行时错误线程“main”中的异常 java.lang.NumberFormatException:零长度 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());
}
}

最佳答案

使用 in.next() 而不是 in.nextLine() 并且不要忘记关闭 Scanner 对象 中。

这是完整的 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();
}

关于java - 如何将字符串转换为bigInteger并存储在哈希集中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42375027/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com