gpt4 book ai didi

java - Java 中的 BigInteger 扫描器输入

转载 作者:行者123 更新时间:2023-12-02 04:26:58 26 4
gpt4 key购买 nike

我只想从Java的扫描仪输入中获取BigInteger,但循环超出了它的限制。如果我想获得两倍的输入,则循环会获得两次,但只打印一次。我想要获取输入并将输入相乘并显示结果。

import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Scanner;

public class Fastmultiplication {

public static void main(String[] args) {
// TODO Auto-generated method stub
BigInteger m = BigInteger.valueOf(1);
BigInteger n = BigInteger.valueOf(1);
Scanner sc = new Scanner(System.in);
Scanner sc1 = new Scanner(System.in);
int in = sc.nextInt();

ArrayList<BigInteger> al = new ArrayList<BigInteger>();

while ((sc.hasNextBigInteger()) && (sc1.hasNextBigInteger()) && (in != 0)) {
in--;
m = sc.nextBigInteger();
n = sc1.nextBigInteger();
al.add(m.multiply(n));

}
System.out.println(al.size());
for (BigInteger integer : al) {

System.out.println(integer);

}
sc.close();
sc1.close();
}
}

最佳答案

我不明白您为什么创建两个 Scanner 对象。但这里是所需的工作代码:

import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Scanner;

public class Fastmultiplication {
public static void main(String[] args) {
BigInteger m, n;
try (Scanner sc = new Scanner(System.in)) {
int in = sc.nextInt();

ArrayList<BigInteger> al = new ArrayList<>();
while (in > 0) {
in--;
m = sc.nextBigInteger();
n = sc.nextBigInteger();
al.add(m.multiply(n));
}

al.stream().forEach((bigInteger) -> {
System.out.println(bigInteger);
});
} catch (Exception e) {
System.out.println("Invalid user input.Going to terminate this program");
}
}
}

关于java - Java 中的 BigInteger 扫描器输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32026965/

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