I am creating a program that calculates how many numbers between A and B are divisible by K. This program should allow the user to input first the number of test cases then get the corresponding A, B, and K values depending on the number of test cases. Sample Input:
2
1
10
3
8
20
4
Output would be:
Case 1: 3
Case 2: 4
However, I keep getting a NullPointerException right after hitting enter after the second line. In this case, I only get to enter:
2
1
Here is the code:
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);
}
}
I've tried other "fixes" such as initializing the Scanner variable or using a new class that implements scanner.nextInt() but none worked for me. Thank you in advance for your help.