Please explain I'm a little confused with do while . If I enter the name of the city the first time, everything works correctly.But if I enter a number, I get a corresponding message, and when I try to enter the name of the city for the second time, it gives the same message.(about invalid data)
String town=scanner.nextLine();
boolean tryagain = false;
do {
if (town.charAt(0) >= '0' && town.charAt(0) <= '9'){
System.out.println("You probably entered an invalid data format");
scanner.nextLine();
tryagain = true;}
else {
tryagain = false;
}
}while (tryagain);
I also tried the try and catch option, but I couldn't write an exception if the user entered numbers instead of a string.It doesn't work. Help please.
try {
System.out.println("enter the name of the city");
town = scanner.nextLine();
} catch (InputMismatchException e) {
System.out.println ("You probably entered an invalid data format ");
scanner.nextLine();
}
CodePudding user response:
Note the difference between this line of code:
town = scanner.nextLine();
and this line of code:
scanner.nextLine();
They both accept input from the console, but only one of them stores that input in the town
variable. To update the town
variable with the newly entered value, store that value in that variable:
town = scanner.nextLine();
CodePudding user response:
Try this. Inside if block save scanner.nextLine() to town variable in order to check in the next iteration if it consists only from numbers or it is empty:
Scanner scanner = new Scanner(System.in);
String town=scanner.nextLine();
boolean tryagain;
do {
if (town.matches("[0-9]*")){
System.out.println("You probably entered an invalid data format");
town = scanner.nextLine();
tryagain = true;}
else {
tryagain = false;
}
} while (tryagain);
CodePudding user response:
put it inside try block and try parsing it as Integer
try{
Integer.parseInt(town)
}catch(NumberFormatException nfe){
//this is a string otherwise it would be number
}