Continuously ask for a user input - java

I have two available options for a user to input, and what I am trying to accomplish is if the user does not enter either of the inputs the program will continuously ask them again until they enter a valid one. Here is the code right now
String userLIB = user_input.next();
if (userLIB.contentEquals(UBC.acro)){
printDetails(UBC);
} else {
if (userLIB.contentEquals(ORL.acro)){
printDetails(ORL);
} else {
while (!userLIB.contentEquals(UBC.acro) || !userLIB.contentEquals(ORL.acro)){
System.out.println("Invalid input");
break;
}
}
}
I have a break to keep the code from looping the "Invalid input" indefinetly but it just ends the program right now which isn't what I want to happen. Is there a way to make the program go back to the start of the if statement?

You're breaking your code when the Invalid input condition is met.
Do as following,
String userLIB = "";
do {
userLIB = user_input.next();
if (userLIB.contentEquals(UBC.acro)){
printDetails(UBC);
} else if (userLIB.contentEquals(ORL.acro)) {
printDetails(ORL);
} else {
System.out.println("Invalid input. Try again!");
}
} while (!userLIB.contentEquals(UBC.acro) || !userLIB.contentEquals(ORL.acro));
This, tries to get the only 2 possible inputs and terminate the loop.
Else will loop again and again, until the required input is provided.

I figured it out with the help of #Carcigenicate, I put a while loop outside of the whole code and then put a userLIB = user_input.next(); inside of the incorrect if statement. Also thanks to #Sridhar for giving an answer that also works

Related

Im trying to make a text based game that looks like a PC terminal, i cant find a way to tell the user if they use a wrong sentence

//Code up
if (userinput.contains(help)) {
//Go on with the game
}
else {
System.out.println("Im sorry , couldnt understand that"); //here is where i want to go back up and
repeat the command
}
I tried almost everything a beginner would know and nothing , do while loops not working in my case (maybe you can find a way) , if i let the if like that the game closes if you get the wrong answer (something out of conttext) , some help would be great! Thx :D
You could use a 'Recursive' function (a function that calls itself).
So in this case, you could do something like:
public void getAndParseInput(){
String userInput = getUserInput() // Use whatever you're using to get input
if(userInput.contains(help)){
// If the user input contains whatever the help is (note: if you're looking for the specific word help, it needs to be in speech marks - "help").
continueWithGame...
}else{
System.out.println("Im sorry , couldnt understand that");
this.getAndParseInput();
}
}
You need to put that code inside a while loop and establish an exit condition.
boolean endGame = false;
/* Here read userinput */
While(!endGame) {
if (userinput.contains(help)) {
//Go on with the game
} else if(userinput.contains("quit"){
endGame = true;
} else {
System.out.println("Im sorry , couldnt understand that"); //here is where i want to go back up and
repeat the command
}
/* Here read userinput */
}
The Below code is similar to your code,reuse the code with appropriate changes as you required.
The code works as below.
1. Scans the input from the console
2. Compares the scanned input with the String "help"
3. If scanned input matches with help, then continue with the execution
4. Otherwise, if the user wants to continue then he can press the
letter 'C' and continues with the execution.
5. If user doesn't press 'C', then the control breaks the while loop
and comes out of the execution
public void executeGame() {
Scanner scanner = new Scanner(System.in);
String help = "help";
while(true) {
System.out.println("Enter the input for execution");
String input = scanner.nextLine();
if (input.contains(help)){
System.out.println("Continue execution");
} else {
System.out.println("Sorry Wrong input.. Would you like to continue press C");
input = scanner.nextLine();
if (input.equals("C")){
continue;
} else {
System.out.println("Sorry wrong input :"+input);
System.out.println("Hence Existing....");
System.exit(0);
}
}
}
}

Why when I have "valid = true;" under How many you want to order, in debug mode it the code works but running it does not?

But if I put it to "valid = false;" it does not work in debug or running.
In fact even running the code, I can't type anything after the "Do you want to order anything else?", no matter if it's in debug or running mode.
Am I missing something? After asking "how many you want to order" and you put in a number after it should ask "do you want to order anything else" which is does but then I can't type and break out of the do while loop. Everything else is working up to that point.
do {
boolean itemValid = true;
while (itemValid) {
System.out.println("Please enter an item name: ");
String enterItem = scnr.nextLine();
if (keepTrack.containsKey(enterItem)) {
System.out.println(keepTrack.get(enterItem));
itemValid = false;
} else {
System.out.println("Sorry we don't exist.");
continue;
}
System.out.println("How many do you want to order?");
int enterQuan = scnr.nextInt();
yourOrder = enterQuan;
valid = false;
}
System.out.println("Do you want to order anything else?");
String yesNo = scnr.nextLine();
if (yesNo.equalsIgnoreCase("n")) {
valid = false;
} else
break;
} while (valid);
Two problems with your code. First, probably unnoticed yet:
do ...
if (keepTrack.containsKey(enterItem)) {
System.out.println(keepTrack.get(enterItem));
itemValid = false;
} else {
System.out.println("Sorry we don't exist.");
continue;
}
When your input is "invalid", you turn into the else branch. The else branch continues the loop. The loop depends on value. Thus: as soon as you start with value=true, and then have an invalid input, you end up with a never-ending loop. Because nothing between the loop start and the continue statement will ever change the conditions that would end the loop.
Your actual question: when you call int enterQuan = scnr.nextInt() that does not consume the "ENTER" that you typed on the console. See here for details.
And there is another problem:
if (yesNo.equalsIgnoreCase("n")) {
valid = false;
} else
break;
}
When the user enters n or N, you go valid=false which ends the outer do-while loop. Thus: when the user enters anything else, the elsepath is taken. What is to be found in the else path? A break. Which also ends the do-while loop.
In other words: your code does exactly what you told it to do: to end the do-while loop, one way or the other.
The real answer is: you need to be much more careful what you put in your code. Each and any character matters. And when you put something into your code for an experiment: remember that it is there, and has effects.

Returning back to the beginning of a loop using "continue" on Java

public void talk() {
String[] prompts = {"Describe to me in a sentence why this is a cool program.",
"Describe to me in a sentence how your day was.",
"Describe to me in a sentence what programming means to you.",
"Describe to me in a sentence why food is neccessary for humans."};
iramInLoop = true;
while(iramInLoop)
{
int i = new Random().nextInt(prompts.length);
System.out.println(prompts[i]);
String input = Raybot.getInput();
if(!checkPunc(input) && !checkCaps(input)){
System.out.println("Check your capitalization and your punctuation!");
}
else{
System.out.println("Great grammar keep it up! Do you want to try again?");
if(input.equals("yes")) continue;
else
{
iramInLoop = false;
Raybot.talkForever();//this exits the loop
}
}
}
}
I am having extreme trouble trying to restart my loop. So at the end of my code when the loop is done running I put a string which asks if the user wants to try again and if the user says yes I want it to go back to the beginning of the loop and do what the loop does again. However, every time I run it it goes to the end of the loop and doesn't even ask for an input.
I think you should be breaking out of the loop if the person guessed right, but then decided not to continue. In this case, your logic should be something like this:
while (true) {
int i = new Random().nextInt(prompts.length);
System.out.println(prompts[i]);
String input = Raybot.getInput();
if (!checkPunc(input) && !checkCaps(input)) {
System.out.println("Check your capitalization and your punctuation!");
}
else {
System.out.println("Great grammar keep it up! Do you want to try again?");
input = Raybot.getInput();
if (input.equals("no")) {
break;
}
}
}
// whatever this does, you intended for it happen after the loop terminates, so do it here
Raybot.talkForever();
You are missing to actually accept any input
maybe
System.out.println("Great grammar keep it up! Do you want to try again?");
input = Raybot.getInput();
change if(input.equals("yes")) continue;
to if(Raybot.getInput().equals("yes")) continue;

Recursion call in java causing incorrect behavior

I have a recursion call which is showing weird behavior.
public String recursionMethod() {
String repeatRun = null;
repeatRun = scanner.next();
if (!("Y".equals(repeatRun) || "N".equals(repeatRun))) {
System.out.println("Please enter the correct value. (Y/N)");
this.recursionMethod();
}
System.out.println("value of the entered variable->"+repeatRun);
return repeatRun;
}
When the method run for the first time, I enter value "no". As expected, it enters the if block and so it calls itself again asking to enter either "Y" or "N". This time, I enter "Y". It does not enter the if block again but the log prints like this.
Do you want to enter another directory? (Y/N)
no
Please enter the correct value. (Y/N)
Y
value of the entered variable->Y
value of the entered variable->no
This behavior is strange. Why is it picking the old value again? On running in debug mode it shows that after the control goes to the return line, it again goes to the line "this.recursionMethod()" which is inside the if block.
Please help me understand and also how to fix this so that my method does not return the previous value.
Try this :
public String recursionMethod() {
String repeatRun = null;
repeatRun = scanner.next();
if (!("Y".equals(repeatRun) || "N".equals(repeatRun))) {
System.out.println("Please enter the correct value. (Y/N)");
return this.recursionMethod();
}
System.out.println("value of the entered variable->"+repeatRun);
return repeatRun;
}
You forgot the return in the if block where you make the recursive call.
When you check if the typed value is Y or N, if the value is wrong, you ask the user to type again a new value, making a recursive call. However, when this recurisve call ends, the method continues till the end, printing the value typed first. The right implementation should be this:
if (!("Y".equals(repeatRun) || "N".equals(repeatRun))) {
System.out.println("Please enter the correct value. (Y/N)");
repeatRun = this.recursionMethod();
}
else {
System.out.println("value of the entered variable->"+repeatRun);
}
return repeatRun;

Keep on prompting user after invalid input

Now I know that there is a thread called "Validating input using java.util.Scanner". I already looked there and that thread only answered 1/2 of my problems. The other half is when someone enters a number greater than 2 I get Array Index Out of Bounds Exception. I just need help on if someone enters a 3 for either row or column, the console should prompt something like this:
"Enter the coordinates to place an 'X'. Row then Column."
//enters 3 and 3
"Please enter a valid input"
It would keep and asking the user for a valid number until he gives one.
Would I need to do something like the !keyboard.hasNextInt() but for integers? And that would run smoothly with the rest of my code?
You could use a do-while loop. Something like
do {
//prompt
//input
} while (input not valid);
Where prompt and input should be replaced by code to prompt the user and accept input. In the while section, check if input is valid.
You're question isn't too clear but I'll try to make sense of it.
I'm assuming you've named your scanner "keyboard"
Before I try running this code, the first problem I can see is this (Note that I grabbed this from your code before you edited the question):
while (board[row][col] != ' ')
{
System.out.println("Already occupied space");
System.out.println("Choose again");
row = keyboard.nextInt();
col = keyboard.nextInt();
}
Earlier, you made sure that the user enters integers. However, you have abandoned that completely in this case.
Assuming you're trying to avoid an error if the user enters something other than an integer, this is what I would do:
while(true){
boolean valid = true;
if(!keyboard.hasNextInt()){
valid = false;
keyboard.next();
}
else{
row = keyboard.nextInt();
}
if(!keyboard.hasNextInt()){
valid = false;
keyboard.next();
}
else{
col = keyboard.nextInt();
}
if (valid && (row > 2 || col > 2)){
System.out.println("Please enter a valid input");
continue;
}
else if(!valid){
System.out.println("Please enter a valid input");
continue;
}
else
break;
}
There are a couple reasons this code might seem a bit long. First off, we're trying to test if the input is an integer before we attempt to store it as an int. Secondly, we want to compare the input after we store it successfully to see if it's less than 3. If the input isn't an integer, the boolean "valid" will be false. The way a compiler works, if valid is false in the if statement it will ignore anything to the right of the &&, avoiding an error.
I admit, this is using some commands that I haven't learned before, so this might not be the most efficient way. But you get the idea :)
P.S. You should probably throw the above code into a method.

Categories

Resources