我正在创建一个程序来计算A和B之间的数字可被K整除的数量。该程序应该允许用户首先输入测试用例的数量,然后获取相应的A,B和K值,具体取决于测试用例数量。 样本输入:
2
1
10
3
8
20
4
输出将是:
Case 1: 3
Case 2: 4
但是,在第二行之后按Enter键后,我一直收到NullPointerException。在这种情况下,我只能输入:
2
1
以下是代码:
import java.util.Scanner;
public class ABK {
public static void cases(int no, int[] first, int[] second, int[] div){
int[] outputs = null;
for(int i = 0; i < no; i++){
for(int x = first[i]; x <= second[i]; x++){
if(x%(div[i]) == 0)
outputs[i]++;
else continue;
}
}
for(int i = 0; i < no; i++){
System.out.println("Case " + (i+1) + ": " + outputs[i]);
}
}
public static void main(String[] args){
int noOfCases = 0;
int[] a = null, b = null, k = null;
Scanner scanner = new Scanner(System.in);
noOfCases = scanner.nextInt();
if(noOfCases < 0 || noOfCases > 1000){
System.out.println("Invalid number of cases. Only numbers from 1 to 100 are allowed.");
System.exit(0);
}
for(int i = 0; i < noOfCases; i++){
a[i] = scanner.nextInt(); //THIS IS WHERE THE NULLPOINTEREXCEPTION APPEARS
b[i] = scanner.nextInt();
k[i] = scanner.nextInt();
}
for(int i = 0; i < noOfCases; i++){
if(a[i] < 1 || a[i] > 1000){
System.out.println("Invalid value of a. Only numbers from 1 to 1000 are allowed.");
System.exit(0);
}
if(b[i] < 1 || b[i] > 1000){
System.out.println("Invalid value of b. Only numbers from 1 to 1000 are allowed.");
System.exit(0);
}
else if(a[i] > b[i]){
System.out.println("Invalid value of b. It must be larger than a.");
System.exit(0);
}
if(k[i] < 1 || k[i] > 1000){
System.out.println("Invalid value of k. Only numbers from 1 to 9999 are allowed.");
System.exit(0);
}
}
cases(noOfCases, a, b, k);
}
}
我已尝试过其他&#34;修复&#34;例如初始化Scanner变量或使用实现scanner.nextInt()的新类但没有一个对我有效。 提前感谢您的帮助。
答案 0 :(得分:0)
您永远不会实例化a
数组。因此,在尝试访问它时会得到一个NPE。
b
和k
会发生同样的异常。
您可以通过
方式实例化数组a = new int[noOfCases];