【问题标题】:problem is while loop is not ending in taking input paragraph using system.in in Java问题是 while 循环没有结束在 Java 中使用 system.in 获取输入段落
【发布时间】:2019-07-28 19:39:51
【问题描述】:

我在使用 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;
  }

}

【问题讨论】:

  • 请在标题中使用正确的大写字母。

标签: java arrays string inputstream user-input


【解决方案1】:

sc 是一个 Scanner 对象。当您将 sc 与 null 进行比较时,您永远不会得到 true,因为 sc 永远不会为 null。此外,您的代码似乎有很多错误。你的问题也不清楚。请提供一个正确的问题... -谢谢 泰詹甘地

Dt:7 月 29 日(阅读您的评论后):

有两部分代码,一个扫描字符,另一个扫描行。因为第一个“while”循环比较 sc(它是一个 Scanner 对象)它永远不会为空,循环永远不会结束。所以相反做的 sc.equals(null) sc.hasNext()

告诉我这是否适合你。

【讨论】:

  • 我想使用 system.in 将 100 个字符串字符作为输入并将其存储在一个数组中。问题是while循环没有结束,程序仍然在while循环中
  • 我编辑了答案。以下是错误的简短摘要: 循环没有结束,因为循环中的条件始终为真。您正在比较: !sc.equals(null) 和 sc 是一个“扫描仪”对象。扫描仪对象永远不能为空,因为您已经对其进行了初始化。在 while 循环中更改条件。
【解决方案2】:

当你使用“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("============================");
            }
        }

【讨论】:

  • 这是用于双类型输入,但我想使用 system.in 将文章作为输入
【解决方案3】:

在您的第一个循环之后,您已经有一个段落数组,所以为什么不清楚为什么需要第二个循环。 我还把扫描仪放在了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);
        }
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-04-03
    • 2014-02-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多