阵列扫描阻止下一个字符串扫描

时间:2013-01-29 21:27:09

标签: java arrays

所以我有这段代码:

  • 我将4个数字插入数组。
  • 我插入后,我想检查哪两个是最大的,哪两个是最小的。
  • 在执行此检查之前,我想询问用户是否要添加新号码。
  • 此数字将替换其他数字之一。

问题是我的代码在此行之后停止:

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

2 个答案:

答案 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()

相关问题