所以我有这段代码:
问题是我的代码在此行之后停止:
System.out.println("Do you wish to add another number [Y/N]?");
我永远不会输入Y或N(“是/否”)。但是,如果我删除它之前的扫描,这是有效的。我使用的import语句是import.util.*;
感谢任何想法或有用的建议!
以下是代码:
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]);
}
答案 0 :(得分:2)
问题是Scanner#nextInt()
和类似的方法不能处理End-Of-Line令牌。一种解决方案是在调用nextLine()
之后简单地调用nextInt()
来处理和丢弃此令牌。
即,
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();
答案 1 :(得分:1)
您希望使用Scanner.next()
而不是Scanner.nextLine()
。