I am making a game and it prompts you for your name and after you type in your name it asks you to confirm it by typing "N" or "Y". After pressing N it doesn't print anything back out although it does take in input but doesn't prompt you to do so as it doesn't print anything else. Only Y works. I have tried everything but it doesn't work.
This is the code I have done to confirm the name:
private static void comfirmName() {
System.out.println("Is " + name + " your name?");
try {
Thread.sleep(1000);
} catch(InterruptedException ex) {
Thread.currentThread().interrupt();
}
System.out.println("Y/N");
if (input.nextLine().toUpperCase().equals("Y")) {
System.out.println("There is something you should know...");
}
if (input.nextLine().toUpperCase().equals("N")) {
System.out.println("Enter your name:");
name = input.nextLine();
System.out.println("Is " + name + " your name?");
}
if (!input.nextLine().toUpperCase().equals("N") && !input.nextLine().toUpperCase().equals("Y")) {
System.out.println("Please enter Y or N");
}
}
This is the output:
Welcome to Enchanted Mage!
Here we will venture into the dangers of this planet!
First of all, you must tell me your name, venturer!
Type in your name:
ots wng
Hello there ots wng!
Is ots wng your name?
Y/N
n
otswng
nothing is hapening
ummm
Please enter Y or N
BUILD SUCCESSFUL
There are no errors but it is really annoying to get any output out.
Just add an input before entering the ifs, just like that:
String inputAnswer = input.nextLine().toUpperCase();
and to be cleaner, just change the input.nextLine inside the ifs to the variable you just created, like that:
if(inputAnswer.equals("Y")){
System.out.println("There is something you should know...");
}
I just tested that and it works. feel free to ask anything else!
Read only once the confirmation.
private static void comfirmName() {
System.out.println("Is " + name + " your name?");
System.out.println("Y/N");
String confirmation = input.nextLine().toUpperCase(); //Read only once the user confirmation
if (confirmation.equals("Y")) {
System.out.println("There is something you should know...");
}
if (confirmation.equals("N")) {
System.out.println("Enter your name:");
name = input.nextLine();
System.out.println("Is " + name + " your name?");
}
if (!confirmation.equals("N") && !confirmation.equals("Y")) {
System.out.println("Please enter Y or N");
}
}
Output
Is Dan your name?
Y/N
n
Enter your name:
Dan
Is Dan your name?
Related
This task is whether a word is a palindrome, and I use java 11.
After entering of the word with spaces the code gives me an answer, but while loop breaks and the code "finishes with exit code 0" If I choose word = sc.next(). But If I write word = sc.nextLine() - It executes well and begins loop again.
I can't understand why, cause I can't debug this part of code, It's just skipped. And I don't understand why this happens. So can somebody explain to me what am I doing wrong?
Maybe there's a way to avoid this spaces?
P.S. I'm new to programming. Thanks to everyone.
try {
Pattern pattern = Pattern.compile("[Y|y][E|e][S|s]");
while (true) {
String word = "";
Scanner sc = new Scanner(System.in);
System.out.println("Enter the word without spaces");
if (sc.hasNext("(?>\\p{Alpha})+")) {
word = sc.next();
System.out.println(word);
System.out.println("The word is correct");
String text2;
StringBuilder sb = new StringBuilder();
text2 = sb.append(word).reverse().toString();
if (word.equalsIgnoreCase(text2)) {
System.out.println("Yes, it's a palindrome." + " " + "Want to try another one?");
System.out.println("Enter yes if you want to continue" + " or " + "enter any symbol if no");
if (sc.hasNext(pattern)) {
}
else {
break;
}
}
else {
System.out.println("No, it's not a palindrome." + " " + "Want to try another one?");
System.out.println("Enter yes if you want to continue" + " or " + "enter any symbol if no");
if (sc.hasNext(pattern)) {
}
else {
break;
}
}
}
else {
word = sc.next();
System.out.println("It's not a word");
System.out.println("Want to try another one?");
System.out.println("Enter yes if you want to continue" + " or " + "enter any symbol if no");
if (sc.hasNext(pattern)) {
}
else {
break;
}
}
}
}
catch (NoSuchElementException ex) {
System.out.println(ex.getMessage());
}
}
What can you improve in your regex, [Y|y][E|e][S|s]?
Use [Yy][Ee][Ss] instead. The [] specifies a character class and all the characters inside it mean one of them i.e. by default they come with an implicit OR. Check this to learn more about it.
How can you determine if the input contains space?
Pass " " to the function, String#contains to determine it.
Demo:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
while (true) {
System.out.print("Enter a word without spaces: ");
String word = sc.nextLine();
if (word.contains(" ")) {
System.out.println("It's not a word");
} else {
System.out.println("The word is correct");
StringBuilder reverse = new StringBuilder(word).reverse();
System.out.println(word.equalsIgnoreCase(reverse.toString()) ? "Palindrome" : "Not a palindrome");
}
System.out.println("Want to try another one?");
System.out.print("Enter yes if you want to continue or any other symbol otherwise: ");
if (!sc.nextLine().matches("[Yy][Ee][Ss]")) {
break;
}
}
}
}
A sample run:
Enter a word without spaces: Hello World
It's not a word
Want to try another one?
Enter yes if you want to continue or any other symbol otherwise: yes
Enter a word without spaces: HELLO
The word is correct
Not a palindrome
Want to try another one?
Enter yes if you want to continue or any other symbol otherwise: YES
Enter a word without spaces: Malayalam
The word is correct
Palindrome
Want to try another one?
Enter yes if you want to continue or any other symbol otherwise: Yes
Enter a word without spaces: papa
The word is correct
Not a palindrome
Want to try another one?
Enter yes if you want to continue or any other symbol otherwise: n
so I am currently having difficult trying to fix this. In short, I'm trying to create a banking application for a class. I'm writing a method to print and get user's inputs but the print lines print out both lines before I can get inputs. Here is my implementation.
boolean done = false;
while(!done) {
System.out.println("Welcome to Running Bank"
+ "\nWhat would you like to do?"
+ "\n1-Create Account"
+ "\n2-Log-In"
+ "\n3-Exit");
choice = scanner.nextInt();
switch(choice) {
case 1:
System.out.println("Input your username(No more than 15 characters: ");
Username = scanner.nextLine();
System.out.println("Input your password(Must be at least 8 characters and not over 24): ");
Password = scanner.nextLine();
}
}
}
What I expected it to do was to print out "Input your username" then after I get the user's input for it then to print the next line. However, what happening right now is that both lines get print before I can put in anything.
Thank you in advanced.
boolean done = false;
while(!done) {
System.out.println("Welcome to Running Bank"
+ "\nWhat would you like to do?"
+ "\n1-Create Account"
+ "\n2-Log-In"
+ "\n3-Exit");
choice = scanner.nextInt();
scanner.nextLine();
switch(choice) {
case 1:
System.out.println("Input your username(No more than 15 characters: ");
Username = scanner.nextLine();
System.out.println("Input your password(Must be at least 8 characters and not over 24): ");
Password = scanner.nextLine();
}
}
}
This should work now. I have added a scanner.nextLine() after inputing choice
I am brand new to coding and trying to get my second program working. It is pretty straight forward as to what it does, but it is throwing an error on line 24 "Duplicate local variable confirm". Can't quite work out why it doesn't like what I'm doing.
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();
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");
char confirm = userInput.next().charAt(0);
if (confirm !='y' || confirm !='n'){
System.out.println("Sorry that input is not valid, please try again");
}
else {
System.out.println(name + "landed in" + country + "at the age of" + age + ".");
}
} while(confirm == 'Y'|| confirm == 'y');
You're declaring confirm twice. Change the second declaration to just assigning to it and you should be OK:
confirm = userInput.next().charAt(0);
// No datatype, so you aren't declaring confirm, just assigning to it
Because your "confirm" variable already defined in the scope (second row). If you want to assign a value, just write confirm = userInput.next().charAt(0);
Another option to fix is to remove the unnecessary declaration char confirm;
And use it only when needed
char confirm = userInput.next().charAt(0);
As #ScaryWombat suggested, you will need to change scope of the variable (currently while is in different scope than do )
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.
I have been researching this problem for a while now and I thought I found a solution, but to no avail.
I am creating a text based game, and when I ask the user to enter their choice as a number 1-4, they have to hit enter twice. I have to hit enter twice whether or not my nextInt() is followed by nextLine() (which is what most of my research has uncovered.)
public void askPlayer() {
int playerLocation = player.getCurrentLocationIndex();
enterRoom(map.getLocationAt(playerLocation));
Scanner sc = new Scanner(System.in);
if(map.hasLeftChild(playerLocation)){
System.out.println ("Press 1 to go to " + map.getLocationAt(map.getLeftChild(playerLocation)).getName());
}
if(map.hasCenterChild(playerLocation)){
System.out.println ("Press 2 to go to " + map.getLocationAt(map.getCenterChild(playerLocation)).getName());
}
if(map.hasRightChild(playerLocation)){
System.out.println ("Press 3 to go to " + map.getLocationAt(map.getRightChild(playerLocation)).getName());
}
if(map.hasParent(playerLocation)){
System.out.println("Press 4 to go back to " + map.getLocationAt(map.getParent(playerLocation)).getName());
}
int choice = sc.nextInt();
sc.nextLine();
System.out.println("You picked " + choice);
super.takeTurn(choice);
}'
Any help is appreciated!
My program basically allows the user to enter grades (elements) which are stored in a Gradebook (array). The user also has the option to change the grades (elements) in the Gradebook (array).
My issue is that once the while loop loops and the user is asked "Make more changes? Enter Yes or No" If I enter yes, then the user asked which grade to change, is allowed to replace the grade, and the modified gradebook prints. However, if I enter "no" just the gradebook prints. Is there a way I can get the program to print "Good bye!" (signaling the end of the program) if the user enters no? I believe I'm supposed reorganize my code and set a while-loop with boolean = false? But I'm not sure how to get started...
Any help would be greatly appreciated. Thank you.
System.out.println("Make changes? Enter Yes or No");
String makeChanges = input.next();
if (makeChanges.equals("no")) {
System.out.println("Good bye!");
}
while (makeChanges.equalsIgnoreCase("Yes")) {
// Ask user if what grade they would like to change
//int index = NumberReader.readPositiveInt(input, "Enter the index of the grade to be changed: (1 to " + grades + ") : ", "Invalid index input", index);
int index = NumberReader.readCappedPositiveInt(input, "Enter the index of the grade to be changed: (1 to " + grades + ") : ", "Invalid index input", numOfGrades);
System.out.println("Enter grade (limit to two decimal places)" + ": ");
// offset the index by one
mogrades[index - 1] = NumberReader.readPositiveDouble(input, "Enter grade " + index + " :",
"Invalid data entered");
System.out.println("The Grade book contains: ");
printArray(mogrades);
System.out.println("Make more changes? Enter Yes or No");
makeChanges = input.next();
System.out.println(makeChanges);
System.out.println("The Grade book contains: ");
printArray(mogrades);
}
}
Break statements are used to exit loops. You could try this in the while loop:
if (makeChanges.equalsIgnoreCase("No")) {
System.out.println("Good Bye!");
break;
}
If you want to exit the entire program, use System.exit(0);
if (makeChanges.equalsIgnoreCase("No")) {
System.out.println("Good Bye!");
System.exit(0);
}
Here is a simple program demonstrating how this would work:
import java.util.Scanner;
public class Simple {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String makeChanges = "Yes";
while (makeChanges.equalsIgnoreCase("Yes")) {
System.out.println("Make more changes? Enter Yes or No:");
makeChanges = input.next();
if (makeChanges.equalsIgnoreCase("No")) {
System.out.println("Good Bye!");
System.exit(0);
}
}
}
}
And here is the output from the command line:
daniel#4.3:StackOverflow$ javac Simple.java
daniel#4.3:StackOverflow$ java Simple
Make more changes? Enter Yes or No:
Yes
Make more changes? Enter Yes or No:
Yes
Make more changes? Enter Yes or No:
No
Good Bye!