Reputation: 189
I want to create a program where you enter a string and it checks if the length is 9 or not. If it is, it gives a message that it is okay. If not, it will give a message that is not, and prompt the user to enter the string again. While running it, I always get that is wrong. Where am I going wrong?
import java.util.*;
public class Sec {
public static void main(String[] args) {
Scanner Secnum = new Scanner(System.in);
System.out.println("Give Sec: ");
String Sec = Secnum.nextLine();
do{
if (Sec.length()!= 9);
System.out.println("Wrong lenght Sec,enter again");
Secnum.nextLine();
}while (Sec.length() == 9);
System.out.println("Sec lenght okay");
}
}
Upvotes: 1
Views: 1929
Reputation: 4131
You are terminating the if statement.
if (Sec.length()!= 9);
So, the next print always executes irrespective of it being true or not.
Put the logic for failure inside an if
block.
if (Sec.length()!= 9) {
// Print failure message
// Other logic
}
Upvotes: 2
Reputation: 5874
You want to request a new value as long as the length is NOT 9.
So your loop should have that as condition. Further your if is incorrect. If in Java needs curly braces else it will effect the next statement only. A statement can be only a semi-colon as well. So your if-statement is completely useless.
To make the code even more compact you can take out the if and swap the do-while loop. That will only run if the condition is true and not once in the beginning no matter the condition.
A code that should work better:
import java.util.*;
public class Sec {
public static void main(String[] args) {
Scanner secnum = new Scanner(System.in);
System.out.println("Give Sec: ");
String sec = secnum.nextLine();
while (sec.length() != 9) {
System.out.println("Wrong lenght Sec,enter again");
secnum.nextLine();
}
System.out.println("Sec lenght okay");
}
}
On a side note: Use lowercase variable names. That is the better code-style :)
Upvotes: 2