簡體   English   中英

循環終止混亂

[英]Loop termination confusion

因此,我有這段代碼可以為序列輸入一系列整數,但是我想知道如何僅通過不輸入任何值並按Enter來終止while循環。 我知道如果x整數值為0,則可以設置終止循環的條件。

public static void main(String[] args) {
SimpleReader in = new SimpleReader1L();
    SimpleWriter out = new SimpleWriter1L();
    Sequence<Integer> s = new Sequence1L<>();
    Sequence<Integer> temp = s.newInstance();
    System.out.println("Enter ");
    int x = in.nextInteger();
    int i = 0;
    while (in.nextLine()) {
        s.add(i, x);
        x = in.nextInteger();
        i++;
    }
    System.out.println(s);
}

如果要實現所描述的內容,則需要更改讀取輸入的方式-不輸入任何內容。

首先有一段while (in.nextLine())從您的輸入中多吃一行。 因此,一半的輸入行都丟失了。

我建議閱讀類似String line = in.nextLine() 然后是這樣的:

if (line.equals("")) break;
int x = Integer.parseInt(line);

抱歉,最近沒有做Java給您整個循環。 但我認為您應該明白。

break可用於退出循環。 所以你可以這樣:

if (x == 0) break; 在聲明i++;之前i++;

使用do while循環,如下所示:

do {
    input = int.nextInteger();
    s.add(i, x);
    i++;
} while (input != 0);

或在您的情況下使用while循環

while (in.nextLine()) {//assuming it checks if user has input
    s.add(i, x);
    x = in.nextInteger();//assuming this api gives integer value back if user indeed entered one
    if (x == 0) 
        break;
    i++;
}

按Enter鍵,沒有任何值。

while (in.nextLine().length() > 0) {
    s.add(i, x);
    x = in.nextInteger();
    i++;
}

循環終止。

您也可以修改一下它,因為=操作返回的值與它設置的值相同:

  SimpleReader in = new SimpleReader1L();
  Sequence<Integer> s = new Sequence1L<>();
  System.out.println("Enter ");
  int i = 0;
  String line = "";
  while (!(line = ir.readLine()).trim().isEmpty()) {
    x = Integer.parseInt(line);
    s.add(i, x);
    i++;
  }
  System.out.println(s);

暫無
暫無

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

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