In my if/else statement I have two if/else statement and two nested if/else statement. When I run the program and input "s" it would skip the first if statement and then jump to the second if statement and jump back to the while loop and never reaches the nested if/else statement. Now what I intended the program to do is when I input "s" and it runs through the first if statement, in theory, it should run through the nested else statement and the output would be "You can't go that way". The program works when I input the correct input "n". Any suggestions?
while(!input.equals("quit")) {
System.out.println(map.rooms[row][col].name);
System.out.print("<");
input = scan.nextLine().toLowerCase();
if (input.equals("n")) {
if (map.rooms[row][col].isValidExit("n"))
row--;
else
System.out.println("There is no exit that way");
} else if (input.equals("e")) {
if (map.rooms[row][col].isValidExit("e"))
row++;
else
System.out.println("There is no exit that way");
}
}
It's clear that the program will never reach the nested if/else statement when your input is 's' because your main if else statement is just processing the 'n' case and the 'e' case , if want it to process other cases and show the message "There is no exit that way" , then your code should be like this :
while(!input.equals("quit")) {
System.out.println(map.rooms[row][col].name);
System.out.print("<");
input = scan.nextLine().toLowerCase();
if (input.equals("n")) {
if (map.rooms[row][col].isValidExit("n"))
row--;
else
System.out.println("There is no exit that way");
} else if (input.equals("e")) {
if (map.rooms[row][col].isValidExit("e"))
row++;
else
System.out.println("There is no exit that way");
}
else
{
// you should process other cases here like "s"
System.out.println("There is no exit that way");
}
}
I think you are misunderstanding how conditional branches work.
When you say
if (input.equals("n")
{
System.out.println("go north");
}
else if (input.equals("e")
{
System.out.println("go east");
}
It will check if the input equals n or not, and if not, it will check the next branch. It will not go into the branch even if it evaluates to false, because otherwise what would be the point of the conditional branch in the first place? You might as well take it out.
I don't think your "intended" logic would make sense either: if a user hits "s", why would the program check whether north is passable? Your design doesn't seem to make sense from a player's perspective.
If you want to have a case for "s", you can just add it as another branch for when the user does enter "s"
else if (input.equals("s"))
{
System.out.println("go south");
}
Related
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.
So i need help, i am trying to input a Y/N program but it is not accepting a big 'Y' or 'N'. Also another thing that i am trying to do is after pressing 'Y'/'y' i am trying to get the program to loop back to the code written above. Example a program that displays '123' and do i need to continue? Y/N, if entered yes it goes back up to restart the program from scratch. Please help me.
System.out.println("continue? Yes or no ");
char check = s.next().charAt(0);
while (check != 'y' && response != 'n')// corrected this part, however need help with restarting the loop back to the first line of code in a loop {
System.out.println("\nInvalid response. Try again.");
check = s.next().charAt(0);
} if ((check == 'n') || (check == 'N')) {
// I tried (check == 'n' || check == 'N')
System.out.println("Program terminated goodbye.");
System.exit(0);
} else if (check == 'y') {
//need help with restarting the loop back to the first line of code in a loop
}
I think this is what you are looking for.
char check;
Scanner scanner = new Scanner(System.in);
do
{
//your piece of code in here e.g.
System.out.println("Printed 123");
System.out.println("Do you wish to continue?[Y/y] or [N/n]");
choice = scanner.next().charAt(0);
}while (check =='Y' || check == 'y');
System.out.println("Program terminated goodbye.");
A do-while loop runs at least once before the condition is checked and so when a user enters either Y or y, then the condition will be true, meaning that they wish for the loop to run again. If the user enters any other value, then the condition will become false since choice is neither Y nor y and the loop will terminate.
Use String.equals() to compare the value of strings, == compares the strings in memory.
If you want to check without case-sensitive, you should convert the char to a String, then do s1.equalsIgnoreCase(s2);
So
while(true) {
System.out.println("Continue? [Y/N]");
char check_char = s.next().charAt(0);
String check = Character.toString(check_char);
while(check.equalsIgnoreCase("y") && !response.equalsIgnoreCase("n")) {
System.out.println("\nInvalid response. Try again.");
check = s.next().charAt(0);
}
if (check.equalsIgnoreCase("n")) {
System.out.println("Program terminated goodbye.");
System.exit(0);
}
}
For returning to the first line, I used a while loop that loops forever.
To the end if it is n then exits, otherwise it returns back to the first line of the loop.
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
Good evening,
I'm at a loss as to why this loop isn't working at all. It's ruining my entire application. below is the code:
System.out.println("Please tell me what to count till?");
do
{
try
{
newEndingValue= input.nextInt();
if(newEndingValue >= 0 || newEndingValue <= 0)
{
break; //breaks the loop
}
}
catch (InputMismatchException e)
{
System.out.println("My Apologies, but COMMAND NOT RECOGNIZED!" + "\nPlease tell me what to count till?");
input.next();
}
}
while(!input.hasNextInt());
v.setEndingValue(newEndingValue);
System.out.println("Please tell me what to count from?");
if(increasingOrDecreasing.equalsIgnoreCase("Increasing")|| increasingOrDecreasing.equals("++") || increasingOrDecreasing.equals("+"))
{
do
{
try
{
newInitialValue = input.nextInt();
if(newInitialValue < v.getEndingValue())
{
break;
}
else{
System.out.println("My Apologies, but starting point value must be smaller than ending point value!" + "\nPlease tell me what to count from?");
newInitialValue = (v.getEndingValue()+10);//overrides the value to something that forces the loop back
}
}
catch (InputMismatchException e)
{
System.out.println("My Apologies, but COMMAND NOT RECOGNIZED!" + "\nPlease tell me what to count from?");
input.next();
}
}
while(!input.hasNextInt() || newInitialValue > v.getEndingValue());
}
else
{
do
{
try
{
newInitialValue = input.nextInt();
if(newInitialValue > v.getEndingValue())
{
break; //breaks the loop
}
else{
System.out.println("My Apologies, but starting point value must be larger than ending point value!" + "\nPlease tell me what to count from?");
newInitialValue = (v.getEndingValue()-10);//overrides the value something that forces the loop back
}
}
catch (InputMismatchException e)
{
System.out.println("My Apologies, but COMMAND NOT RECOGNIZED!" + "\nPlease tell me what to count from?");
input.next(); //consumes the erroneously typed string value
newInitialValue = (v.getEndingValue()-10);
}
}
while(!input.hasNextInt() || newInitialValue < v.getEndingValue());
}
So the output is when entered a no, and then 1000 as follows:
Please tell me what to count till?
no
My Apologies, but COMMAND NOT RECOGNIZED!
Please tell me what to count till?
1000
Please tell me what to count from?
My Apologies, but starting point value must be smaller than ending point value!
Please tell me what to count from?
Why is it going straight to the second written else statement?
Why is it skipping user entry for newInitialValue?
Please note that if edit code after ending value block to below after entering a string for newEndingValue and then correctly enter a number, this rids me of my error but generates another one if ran again and the user cooperates:
...
newInitialValue = input.nextInt(); //essentially gets skipped over by compiler only when previous catch statement is triggered
System.out.println("Please tell me what to count from?");
if(increasingOrDecreasing.equalsIgnoreCase("Increasing")|| increasingOrDecreasing.equals("++") || increasingOrDecreasing.equals("+"))
{...
additionally since its printing out "but starting point value must be smaller than ending point value" we can deduce its working with if(incre...) loop and the do and try loops respectively. But its skipping the (newI... = input...) and the if(newIntia...) lines of code. i know this cause even manually entering in newInitialValue = 2 (within paramenter) it still goes to this else clause.
-_- So the issue is within the while statements:
while(!input.hasNextint())
this looks ahead and checks the next user input, but since the catch consumed one it looks to the next next and it gets murky... essentially if i don't use this it works.
instead i used:
while(isError == true)
and under the do loop with the nested if statement i have:
if(blah blah blah){
isError=false;
break;
and before the next loop block i simply override the isError
isError=true;
//next block of code
The problem here is that you say to java do something if value 1 is true or value2 is true or value3 is true,and then you say on the else to do the same if using or.You got to understand that you need to use and && in order to help java to understand the else parameter.
import java.util.Scanner;
public class SherlockHolmes {
String answer = "Watson";
String response = " ";
int tries = 0;
int tries = 3;
Scanner input = new Scanner(System.in); {
System.out.print("Enter the name of Sherlock's partner, and dear friend.");
response = input.nextLine();
tries++;
if (response.equals("Watson"))
else
while (tries <= 3)
System.out.print("Ooooh, sorry kid! Try again!"); {
System.out.println("Yes, that's right, Barrel Rider.");
break;
} else if (tries == 3) {
System.out.println("Ooooo, sorry kid. But, it looks like you're S.O.L!");
break;
}
}
}
My biggest question is why I'm getting two errors with this method, the error
being: SherlockHolmes.java:16: error: 'else' without 'if'
else
^
SherlockHolmes.java:24: error: 'else' without 'if'
else if(tries == 3)
^
2 errors
I put if code in every line, yet its telling me : "Else without if" for both entries of "else". I am kind of frustrated, and I don't slagging get how Java thinks I have no if when it is clearly there!
What am I doing wrong that Java thinks I have no if code fashioned in?
If you want an if statement with an empty body, you NEED curly braces in Java. Honestly, you should just have way more braces in your code. I strongly suggest reading up on Java coding conventions http://www.oracle.com/technetwork/java/codeconventions-150003.pdf
Example:
if (response.equals("Watson"))
else while (tries <= 3)
For that empty if to compile, you need:
if (response.equals("Watson")) {
}
else while (tries <= 3) {
// loop body
}
You have many syntax errors.
First, you cannot attach an else-if to a while block. Second, if you're trying to make it so that if the response does not equal "Watson", then use the "not equal to" operator, which is simply "!" (an exclamation mark).
Control flow is made up of
if (condition) {} Must be used once, and must be first
else if (condition) {} as many times as you want, optional, must be in between else and if if included
else {} optional, must be last and used once if included
Curly braces and order are mandatory. In Java, it is best practice, and usually required to put curly braces around all blocks: if, while, for. Another thing you need to know is that while loops are not the same as conditionals. They can't be attached to else or else if statements. So your while loop needs to change to
while (tries <= 3) {
...
}
Do this similarly with the conditional statements.
System.out.print("Enter the name of Sherlock's partner, and dear friend.");
response = input.nextLine();
tries++;
while (tries <= 3) {
if (response.equals("Watson")) {
System.out.println("Yes, that's right, Barrel Rider.");
}
else {
System.out.print("Ooooh, sorry kid! Try again!");
break;
}
if (tries == 3) { // If the while loop finishes
System.out.println("Ooooo, sorry kid. But, it looks like you're S.O.L!");
break;
}