簡體   English   中英

問題是while循環不會以使用Java中的system.in獲取輸入段落而結束

[英]problem is while loop is not ending in taking input paragraph using system.in in Java

我在使用System.in將小孔段落作為java中的輸入並將其存儲在數組中時遇到問題。 但是問題是while循環沒有結束並且程序卡在了循環中。 我嘗試了很多方法,但是循環沒有結束。

Scanner sc = new Scanner(System.in);

ArrayList < String > al = new ArrayList<>();

System.out.print("Please Enter Paragraph + \n");
while (!(sc.equals(null))) {
  al.add(sc.next());
}

Scanner sc = new Scanner(System.in);
String para = sc.nextLine();
int x = 0;

while (para != null) {

  if (sc.hasNextLine()) {
    ParaArray[x] = para;
    para = sc.nextLine();

    x++;
  } else {
    para = null;
  }

}

sc是Scanner對象。 當您將sc與null進行比較時,您將永遠不會得到true,因為sc永遠不會為null。 另外,您的代碼似乎有很多錯誤。 您的問題也不清楚。 請提供正確的問題...-謝謝Tejan Gandhi

Dt:7月29日(閱讀您的評論后):

代碼分為兩部分,一個部分掃描字符,另一部分掃描行。.因為第一個“ while”循環比較sc(這是一個Scanner對象),所以它永遠不能為null,循環也永遠不會結束。 .equals(null)sc.hasNext()

告訴我這是否適合您。

當您使用“ sc.hasNextline”時,應在判斷語句之前放置“ Scanner sc = new Scanner(System.in);”,如下所示:

int num = 0;
        while (true) {
            System.out.println("Please input a number");
            Scanner sc = new Scanner(System.in);
            if (sc.hasNextDouble()) {
                num = sc.nextDouble();

            } else {
                System.out.println("It is not a number,please try again!");
                System.out.println("============================");
            }
        }

在第一個循環之后,您已經有一系列的段落,因此為什么不清楚為什么需要第二個循環。 我也把掃描儀在try ()因為掃描儀是Closeable ,因此在年底被關閉。

import java.util.ArrayList;
import java.util.Scanner;

public class ScanTest {
    public static void main(String[] args) {
        try (Scanner sc = new Scanner(System.in)) {

            ArrayList<String> al = new ArrayList<>();

            while (true) {
                System.out.println("Please Enter Paragraph + \n");
                String readLine = sc.nextLine();
                if (readLine.length() == 0) {
                    break;
                }
                al.add(readLine);
            }

            System.out.println("result:"+al);
        }
    }
}

暫無
暫無

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

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