It seems apart from re-declaration of the variable confirm
there are one or more issue -
Issue 1:
After int age = userInput.nextInt()
. It won't prompt for country input and will prompt Press Y to continue or N to start over
.
Cause of this issue:
Since you are using int age = userInput.nextInt();
the scanner will only take the integer value from the input and will skip the \n
newline character.
Fix
As a workaround, I've added userInput.nextLine();
after int age = userInput.nextInt();
such that it will consume the \n
character after nextInt()
.
Issue 2:
After the 1'st iteration, this line will cause issueconfirm = userInput.next().charAt(0);
.
Cause of this issue:
In 2'nd iteration you won't get a prompt to enter the name as the line String name = userInput.nextLine();
will take \n
from the last iteration as input and will skip and prompt for age How old are you?
.
Fix
As a workaround, I've added userInput.nextLine();
after confirm = userInput.next().charAt(0);
such that it will consume the \n
character after userInput.next().charAt(0)
and the next iteration will go as expected.
Issue 3:
This logic if (confirm !='y' || confirm !='n')
expects only y
and n
in lowercase
but here while(confirm == 'Y'|| confirm == 'y')
you are expection y
and Y
both.
Fix - I've added the necessary changes in the code below but would recommend you do change it to a switch case.
NOTE:
It is not recommended to do userInput.nextLine()
after every input and you could simply parse it. See here for further information.
I'm not recommending it but this will get you program working
Scanner userInput = new Scanner(System.in);
char confirm;
do {
System.out.println("Welcome to the story teller");
System.out.println("What is your name?");
String name = userInput.nextLine();
System.out.println("How old are you?");
int age = userInput.nextInt();
userInput.nextLine(); //adding this to retrieve the \n from nextint()
System.out.println("What country would you like to visit?");
String country = userInput.nextLine();
System.out.println("Great! So your name is " + name + ", you are " + age
+ "years old and you would like to visit " + country + " ?");
System.out.println("Press Y to continue or N to start over");
confirm = userInput.next().charAt(0);
userInput.nextLine(); //adding this to retrieve the \n this will help in next iteration
System.out.println(name + " landed in " + country + " at the age of " + age + ".");
if (confirm == 'y' || confirm == 'Y') {
continue; // keep executing, won't break the loop
} else if (confirm == 'n' || confirm == 'N') {
break; // breaks the loop and program exits.
} else {
System.out.println("Sorry that input is not valid, please try again");
// the program will exit
}
} while (confirm == 'Y' || confirm == 'y');
}
Recommending that you use switch case instead of if comparasion of confirmation
and parse the character and integer input and remove the arbitary userInput.nextLine()
added as workaround.