So I have this code:
- I insert 4 numbers into an array.
- After I’ve inserted those, I want to check which two numbers are the biggest and which two are the smallest.
- Before doing this check, I want to ask the user whether they want to add a new number.
- This number would replace one of the other numbers.
The problem is that my code just stops after this line:
System.out.println("Do you wish to add another number [Y/N]?");
I never get to enter Y or N (“Yes/No”). However, this works if I remove the scans before it. The import statement that I use is import.util.*; Any idea or helpful advice is appreciated!
Here’s the code:
Scanner sc = new Scanner (System.in);
int[] array;
array = new int[4];
System.out.println("Enter nr1:");
array[0] = sc.nextInt();
System.out.println("Enter nr2:");
array[1] = sc.nextInt();
System.out.println("Enter nr3:");
array[2] = sc.nextInt();
System.out.println("Enter nr4:");
array[3] = sc.nextInt();
System.out.println("Do you wish to add another number [Y/N]?");
String answer = sc.nextLine();
if ("N".equals(answer)){
Arrays.sort(array);
System.out.println(Arrays.toString(array));
System.out.println("Samllest value: " + array[0]);
System.out.println("Second smalles value: " + array[1]);
System.out.println("Second biggest value: " + array[2]);
System.out.println("Biggest value: " + array[3]);
}
You want to be using
Scanner.next()notScanner.nextLine().