簡體   English   中英

為什么該數組使用scanner在java中顯示兩個索引

[英]why is it that array display two index in in java using scanner

import java.util.Scanner;

public class test{

 public static void main(String[] args)
 {
 Scanner input = new Scanner(System.in);
 System.out.println("Enter maximum number : ");
 int items = input.nextInt();
 String arr[] = new String[items]; 
int x = 0;
 while(x < items)
 {

    System.out.println("Enter item  " + x + ":");
    arr[x] = input.nextLine();
    x++;
  }
}
}

在我的代碼中,首先是我在數組索引中詢問最大數量並存儲到arr []。 現在,當我按下Enter鍵並顯示“輸入項目0”“輸入項目1”時,我發現錯誤。 它顯示索引arr [1]。 應該顯示的是僅在我第一次按Enter時“輸入項目0”。 有人知道嗎?

謝謝

問題是nextInt()掃描程序方法不處理行尾(EOL)令牌,因此當你調用input.nextInt()只有在調用input.nextLine()它才會被懸空。 確實處理EOL令牌。

一種解決方案是顯式調用nextLine()來處理懸空令牌並允許掃描程序為下一個完整的輸入行做好准備:

int items = input.nextInt();
input.nextLine(); // add this

創建一行文本並按<enter> ,文本末尾會附加一個1-2個字符。 一個常見的稱為換行,或LF,用數字表示為十進制10,用字符表示\\n ,另一個稱為回車或CR,用數字表示為13,並且字符為作為\\r Unix和Apple OS系統通常僅附加LF,而Windows / DOS系統將LF和CR附加在一起。

如果在一行文本上調用input.nextInt() ,則掃描程序將獲取int文本,但不會獲取上面提到的行標記或字符的結尾,並且這些字符將保持懸空或未處理。 如果您調用input.nextInt()並且下一行有更多數字輸入,則掃描程序將跳過EOL標記並獲取數字文本,但如果您調用input.nextLine()則掃描程序將獲取EOL令牌,沒有別的。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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