【问题标题】:Java - input data only working if an output statement exists?Java - 仅当存在输出语句时输入数据才有效?
【发布时间】:2015-04-14 06:28:55
【问题描述】:

编辑:使代码更好一点,删除背景故事,改写问题。

所以我让一切正常,但后来转移到另一台计算机,它停止工作。因为这是为了分数,我不想交出一个可能会在我教授的电脑上停止运行的程序。

这就是我想要做的——我想连续输入数据,直到在空行上按下输入。

我真正的问题是这个。为什么它只有在 readLine 命令之后有 print 语句时才起作用?为什么这在别人的电脑上不起作用? (会不会是我从 IDE 运行的?JCreator 4.5 可以,学校电脑上的 JCreator 4 不行。)

import java.util.*;
import java.io.*;

public class TestIfWorks {  
public static ArrayList<String> getArrList() {
    String input = "Empty";

    ArrayList<String> info = new ArrayList<String>();
    BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
    boolean go = true;
    while (go) {
        try {
            input = in.readLine();
            System.out.print(">"); //This causes it to work on my computer, but not on other computers. What!?!

        } catch (Exception e) {
            System.out.println("ERROR:  key read problem");
        }
        if (input.equals("")) go = false;
        else info.add(input);
    }
    return info;
}

public static void inputmethod() {
    System.out.println("Please enter a brief summary if desired. Press enter on an empty line to stop entering data.");
    ArrayList<String> info = new ArrayList<String>();
    info = getArrList();
    System.out.println("Now printing the arraylist out.");
    for (int i = 0; i < info.size(); i++) {
        System.out.println(info.get(i));
    }
}

public static void main(String[] args) {
    inputmethod();
}}

所以是的,它喜欢循环一次,输入该数据,然后在第二个循环中它总是认为您没有输入任何内容,因此只存储第一个数据。除非有输出语句。然后它喜欢工作,但只是有时。

发生了什么?

【问题讨论】:

  • 您正在为不需要的每一行创建一个新的缓冲读取器。尝试在 inputmethod 中创建 Bufferedreder 并将其传递给 getStringLine
  • 这真是糟糕的设计。您正在为每一行创建阅读器。先试着做一个好的设计

标签: java loops input enter


【解决方案1】:

我认为你应该开始使用

if(str != null &amp;&amp; !str.isEmpty())

为了查看它是否为空 你也应该添加

tempStr = "";

在 if else 阻塞之后,因为如果出现问题,您的 tmpStr 仍将具有上次循环状态的值。

如果我是你,我会试试这个:

String input = System.console().readLine();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-18
    • 1970-01-01
    • 1970-01-01
    • 2016-07-22
    • 2023-01-19
    相关资源
    最近更新 更多