简体   繁体   中英

array scan preventing next string scan?

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]);
}

The problem is that Scanner#nextInt() and similar methods do not handle the End-Of-Line token. One solution is to simply call nextLine() after calling nextInt() to handle and discard this token.

ie,

System.out.println("Enter nr1:");
array[0] = sc.nextInt();
sc.nextLine();

System.out.println("Enter nr2:");
array[1] = sc.nextInt();
sc.nextLine();

System.out.println("Enter nr3:");
array[2] = sc.nextInt();
sc.nextLine();

System.out.println("Enter nr4:");
array[3] = sc.nextInt();  
sc.nextLine();

System.out.println("Do you wish to add another number [Y/N]?");
String answer = sc.nextLine();

您要使用Scanner.next()而不是Scanner.nextLine()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM