简体   繁体   中英

Java - input data only working if an output statement exists?

EDIT: Made the code a little nicer, deleted backstory, rephrased question.

So I had everything working, but then moved to a different computer, and it stopped working. Because this is for marks, I don't want to hand in a program that could possibly stop not work on my prof's computer.

So here's what I'm trying to do - I want to input data continuously, until enter is pressed on an empty line.

My real question is this. Why does it only work when the print statement is there after readLine command? And why does that not work on someone else's computer ? (Could it be that I'm running from the IDE? JCreator 4.5 it works, JCreator 4 on the school computer didn't.)

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();
}}

So yeah, it likes to loop once, enter that data fine, then on the second loop it always thinks you're entering nothing, and so only the first data is stored. Unless the output statement is there. Then it likes to work, but only sometimes.

What is happening?

I think you should start using

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

in order to see if it's empty or not also you should add

tempStr = "";

after your if else block because if something goes wrong your tmpStr will still have the value from last loop state.

If i were you i'd try this instead:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM