簡體   English   中英

數組掃描阻止下一個字符串掃描?

[英]array scan preventing next string scan?

所以我有這段代碼:

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

問題在於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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM