Issue
I'm trying to make some distributed java RMI program, where I encountered a problem when I need to take input from the user. In the following code snippet, entering 1
seems to be good, but entering 2
first time cause nothing to print, when I entered 2
again, then it worked.
How did that happened? Checked the BufferedReader.readLine()
function documentation but didn't find anything relate to this. Does this have anything to do with else if
?
import java.io.*;
public class test {
private static BufferedReader lineOfText = new BufferedReader(new InputStreamReader(System.in));
public test() throws NumberFormatException, IOException {
System.out.println("1 to create an auction, 2 to close an auction");
if (Integer.parseInt(lineOfText.readLine()) == 1) {
System.out.println("1 recieved");
} else if (Integer.parseInt(lineOfText.readLine()) == 2) {
System.out.println("2 recieved");
} else {
return;
}
}
public static void main(String[] args) throws NumberFormatException, IOException {
test t = new test();
}
}
input 1
:
1 to create an auction, 2 to close an auction
1 //<- that's the input
1 recieved
input 2
:
1 to create an auction, 2 to close an auction
2 //<- that's the input yet nothing happened
2 //<- input again
2 recieved
Also tried the code snippet on some online compiler and the result is the same as my VSCode. This might be a simply problem but I don't know what happened ;\
Solution
Because you are calling "readline()" in both your "if" and "else-if", it will call readline() twice each time it tries to check for the condition: once when it runs the "if" condition, then a second time when running the else-if. When you place a function in the conditional statement like:
if(myFunction() == true){}
it will ALWAYS run that function before comparing its return value to the condition. So when you have:
if (Integer.parseInt(lineOfText.readLine()) == 1) {
System.out.println("1 recieved");
} else if (Integer.parseInt(lineOfText.readLine()) == 2) {
System.out.println("2 recieved");
} else {
return;
}
It will call readLine() both when it checks the "if", and again at the "else-if".
You should call readline BEFORE you begin checking it against conditions to ensure it is only ran once:
import java.io.*;
public class test {
private static BufferedReader lineOfText = new BufferedReader(new InputStreamReader(System.in));
public test() throws NumberFormatException, IOException {
System.out.println("1 to create an auction, 2 to close an auction");
String myLine = lineOfText.readLine(); //call readLine() before checking conditions so it only runs once
if (Integer.parseInt(myLine) == 1) {
System.out.println("1 recieved");
} else if (Integer.parseInt(myLine) == 2) {
System.out.println("2 recieved");
} else {
return;
}
}
public static void main(String[] args) throws NumberFormatException, IOException {
test t = new test();
}
}
Answered By - Ryan Millares
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.