I am trying to take input of an array of strings (each string is a question) and my code is as follows:
void read_quest()throws IOException
{
System.out.println("enter the questions(enter null to end input operation)");
for(int i = 0;; i++)
{
question[i]=in.readLine();
if(question[i].equals("\0")==true)
{
n=i-1;
break;
}
}
}
but the loop is never exited i am using bluej as it is for a school project(we are allowed to use only bluej) thanks in advance
In Java, you don't have to deal with "\0". Also, it might be hard for the user to input NUL character anyway.
The method in.readLine() returns a String that was input by the user, excluding the end-of-line character that terminates it.
If you want to check if user presses Enter without entering any text, compare the input with the empty string "" like this:
if ("".equals(question[i]))
If you want to check for Ctrl+D (End of transmission character), compare with \4 as said in this post:
if ("\4".equals(question[i])).
Note: cannot test this in Eclipse, and the user will have to press Enter anyway after Ctrl+D
Note that if the user uses Ctrl-C, your readLine() will return null, and your program will exit not long after.
Side notes:
you don't need ==true, because x.equals(y) already is a boolean.
"literal".equals(variable) is safer than variable.equals("literal"): if your variable is null, the first version just yields false without crashing, while the second version throws NullPointerException.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With