Reputation: 5
What could be wrong in this code? The test system of the exercise throws the following error
call to the getIntegers () method printed a value of" null ", but" [1,2,3,4,5, 6] "expected. Tip: Check your spaces and / or spelling.
Could it be the private static scanner scanner = new scanner (System.in);
since I use it in the main but the system does not allow adding the main, since it brings it by default?
import java.util.Scanner;
import java.util.Arrays;
public class formato {
public static int[] getIntegers(int capacity) {
static Scanner scanner = new Scanner(System.in);
int[] array = new int[capacity];
System.out.println("Enter "+capacity+" integer values:\r");
for(int i = 0; i<array.length ; i++){
array[i] = scanner.nextInt();
}
return array;
}
public static void printArray(int[] array) {
for (int i = 0; i < array.length; i++) {
System.out.println("Element " + i + " contents " + array[i]);
}
}
public static int[] sortIntegers(int[] array) {
// int[] sortedArray = new int[array.length];
// for(int i=0; i<array.length; i++) {
// sortedArray[i] = array[i];
int[] sortedArray = Arrays.copyOf(array, array.length);
// }
boolean flag = true;
int temp;
while (flag) {
flag = false;
for (int i = 0; i < sortedArray.length - 1; i++) {
if (sortedArray[i] < sortedArray[i + 1]) {
temp = sortedArray[i];
sortedArray[i] = sortedArray[i + 1];
sortedArray[i + 1] = temp;
flag = true;
}
}
}
return sortedArray;
}
}
Upvotes: 0
Views: 246
Reputation: 1
So the place where this error has occurred gives input as "1 2 3 4 5 6" (on checking user logs, input is given as "1 2 3 4 5 6" & not [1,2,3,4,5,6]), so the part where error has arose is "sc.nextLine()" or "sc.nextInt()" being used. The problem is resolved if "sc.next()" is used.
For explanation of difference between next & nextLine/nextInt of scanner, you could view What's the difference between next() and nextLine() methods from Scanner class?
Upvotes: 0
Reputation: 34
Define a class constant:
public static final Scanner scanner = new Scanner(System.in);
This will help you.
or else just use Scanner scanner = new Scanner(System.in);
Upvotes: 1