As part of my homework, I need to make a program that requires user input. For now I’m sticking with the console, however I’d like to avoid a crash due to newline characters.
This is a test, it acts similarly to what I’m trying to do and crashes due to even one newline character
public void testRead() {
Scanner input = new Scanner(System.in);
String s1 = "", s2 = "", s3 = "", s4 = "", s5 = "";
while (s1 == "" || s1 =="\n")
if (input.hasNext()) {
s1 = input.nextLine();
}
while (s2 == "" || s2 =="\n")
if (input.hasNext()) {
s2 = input.nextLine();
}
while (s3 == "" || s3 == "\n")
if (input.hasNext()) {
s3 = input.nextLine();
}
while (s4 == "" || s4 == "\n")
if (input.hasNext()) {
s4 = input.nextLine();
}
while (s5 == "" || s5 == "\n")
if (input.hasNext()) {
s5 = input.nextLine();
}
// Here is why it might crash
if (input.hasNextInt()) // even though it should not pass this if
// However the if is not the issue.
// This input may even be in another function
int crash = input.nextLine();
System.out.println("s1: " + s1);
System.out.println("s2: " + s2);
System.out.println("s3: " + s3);
System.out.println("s4: " + s4);
System.out.println("s5: " + s5);
}
}
I hoped the while statement would solve it, but it does not.
I could solve the crash, but that would not fix the problem since I would still have empty strings and what not.
Example
This is the first string
This is the second string
<- pressed enter again, by mistake or not
This is the third string
This is the fourth string
Output
s1: This is the first string
s2: This is the second string
s3:
s4: This is the third string
s5: This is the fourth string
// now crash. Again, the crash can be avoided, but I still have a problem where string 3 has not been read or contains …. something I don’t want.
Is there an easy way of solving this issue ? if there is no easy way, I would rather ignore it and finish my homework fast, but I would still like to know the long answer for future reference.
you cannot use
==for string contents equality, try this for ex: