[英]array scan preventing next string scan?
所以我有这段代码:
问题是我的代码仅在此行之后停止:
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]);
}
问题在于Scanner#nextInt()
和类似方法无法处理行尾令牌。 一种解决方案是在调用nextInt()
之后简单地调用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();
您要使用Scanner.next()
而不是Scanner.nextLine()
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.