【问题标题】:Java stop reading after empty lineJava在空行后停止读取
【发布时间】:2011-10-05 15:51:38
【问题描述】:

我正在做一个学校练习,但我不知道如何做一件事。 根据我的阅读,扫描仪不是最好的方法,但由于老师只使用扫描仪,所以必须使用扫描仪来完成。

这就是问题所在。 用户将文本输入到数组中。这个数组最多可以有 10 行,用户输入以空行结束。

我已经这样做了:

 String[] text = new String[11]
 Scanner sc = new Scanner(System.in);
 int i = 0;
 System.out.println("Please insert text:");
 while (!sc.nextLine().equals("")){
        text[i] = sc.nextLine();
        i++;        
    }

但这无法正常工作,我无法弄清楚。 理想情况下,如果用户输入:

This is line one
This is line two

现在按回车键,打印它应该给出的数组:

[This is line one, This is line two, null,null,null,null,null,null,null,null,null]

你能帮帮我吗?

【问题讨论】:

    标签: java


    【解决方案1】:
     while (!sc.nextLine().equals("")){
            text[i] = sc.nextLine();
            i++;        
     }
    

    这会从您的输入中读取两行:将其与空字符串进行比较,然后将另一行实际存储在数组中。您想将该行放在一个变量中,以便在两种情况下检查和处理相同的String

    while(true) {
        String nextLine = sc.nextLine();
        if ( nextLine.equals("") ) {
           break;
        }
        text[i] = nextLine;
        i++;
    }
    

    【讨论】:

    • 不要忘记在你的 while break 中最多输入 10 行。
    【解决方案2】:

    这是典型的 readline 习惯用法,应用于您的代码:

    String[] text = new String[11]
    Scanner sc = new Scanner(System.in);
    int i = 0;
    String line;
    System.out.println("Please insert text:");
    while (!(line = sc.nextLine()).equals("")){
        text[i] = line;
        i++;        
    }
    

    【讨论】:

      【解决方案3】:

      当您尝试输入超过 10 个字符串而不提示 OutBoundException 时,以下代码将自动停止。

      String[] text = new String[10]
      Scanner sc = new Scanner(System.in);
      for (int i = 0; i < 10; i++){ //continous until 10 strings have been input. 
          System.out.println("Please insert text:");
          string s = sc.nextLine();
          if (s.equals("")) break; //if input is a empty line, stop it
          text[i] = s;
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-08-16
        • 1970-01-01
        相关资源
        最近更新 更多