Creating while-loop with nested loops in it - java

I am trying to create a program that picks a random number, and as the user inputs guesses, the program dictates if it's "too high", "too low", AND keeps a running total. But my while loop only extends over the first nested loop I create, and won't cover anything after that.
I'm coding in Blujay on my mac, but received that same issue on a windows desktop, making me believe its a coding error, not a program one
System.out.println("Would you like to play this game? y/n");
Scanner scan = new Scanner(System.in);
playGame = scan.next().charAt(0);
while (playGame == 'y')
System.out.println("Please enter a number in 1-100 range");
userNumber= scan.nextInt();
while in Java, the while loop in the code below only cover(or goes purple / gets highlighted) the line with "while (playgame == y)", and the following print statement, but i need the whole program to be under a while loop so the game can repeat as long as the user says "y".

To make this valid Java code, you first need semicolons at the end of every statement. That's not the fix for your while loop, and maybe in you actual code you already have that, but I'm just pointing it out.
To make a while loop - or any kind of code block - cover multiple statements in Java, you use curly braces {}. Again, maybe your actual code has this, but the way you're wording your question makes me think you probably don't. So that's:
while (condition) {
statement1;
statement2;
...
}
Java does not care about indentation at all, you need the braces and semicolons to make this work.

Wrap the whole code in a while(true) statement and exit it when the user chooses to exit the game:
char playGame;
while (true) {
System.out.println("Would you like to play this game? y/n");
Scanner scan = new Scanner(System.in);
playGame = scan.next().charAt(0);
if (playGame != 'y') break;
System.out.println("Please enter a number in 1-100 range");
int userNumber = scan.nextInt();
System.out.println("You entered: " + userNumber); // or something else
}

Related

How to stop a user from entering a letter in a switch case when the letter is the first input entered

When using a switch case with integers, I am able to successfully stop the user from crashing the program with a try/catch when they enter a letter (a, b, c, etc, not case specific). However, I can only stop it after an integer is entered. For this example, it is NOT my actual code, it is only an example as it is a general question. Secondly, I want to try and get it working with suggestions, not having it done for me:
int choice
Scanner scan = new Scanner (System.in);
System.out.println ("Enter a number");
System.out.println ("1: Example one");
System.out.println ("2: Example two");
System.out.println ("0: Exit");
choice = scan.nextInt();
Loop: for (;;)
{
switch (choice)
case 1: System.out.println ("Example one successful");
choice = scan.nextInt();
break;
case 2: System.out.println ("Example two successful");
choice = scan.nextInt();
break;
case 0: System.exit (0);
break Loop;
default: try
{
System.out.println ("Please enter a number")
choice = scan.nextInt();
}
catch (InputMismatchException error)
{
System.out.println ("Not a valid number: " + error);
choice = scan.nextInt();
}
If the user enters a "1", it outputs the proper text inside the case 1 block. The same goes for case 2 and case 0 to exit. It will loop properly and continuously like this:
Enter a number: 1
Example one successful
Enter a number: 1
Example one successful
Enter a number: 2
Example two successful
Enter a number: ghdrf
Not a valid number: java.util.InputMismatchException
Enter a number: 0
The try/catch works in catching the wrong input, all the other case work. The problem is if the user never enters an integer from the start and enters a letter instead. It will throw the InputMismatchException right away. The try/catch doesn't even try to catch it.
My thinking was because I assigned the scanner to read an integer from the start. I tried to start there. I originally tried this between the loop label and the switch statement as it is the only place I could put it to not get an error:
Loop: for (;;)
{
String letter = input.nextLine();
if(letter.matches("[1-9]*")
{
choice = Integer.valueOf(letter);
}
else
{
System.out.println("Invalid input");
}
switch (choice)
...
This worked somewhat in the same way as my try/catch except it was simply printing "invalid input" with each selection (because of my print statement, I know that). But the same problem was occurring. If a letter was input instead of an integer right off the bat, it would throw an InputMismatchException. I have a feeling it has something to do with what is in the scanner. I've tried experimenting with "next(), nextLine(), nextInt(), equals()" and I've tried parsing with "Integer.valueOf()" trying to get the current line in the scanner to check it or parse it.
This leads me to my questions:
Am I correct to assume that the scanner is reading the input and throwing the exception before I have a chance to catch it?
How do I read the first line in the scanner at the beginning of the program in order to check if it is an integer or a String? I'm not a big fan of skipping the first line because then it causes the user to have to input their number twice in order for the program to print out a message such as:
Enter a number: 1
Enter a number: 1
Example one successful
Any input is greatly appreciated, thank you!
Question #1: no. The problem is, that the exception occurs in those lines which are not surrounded by try-catch (e. g. before the loop, in case 1 or case 2).
Question #2: to read a line, use Scanner#nexLine(). There's no need to have the user to perform his input twice.
Hint: write a method that requests an int value from the user and that returns only, if he entered a correct value.
You have 2 calls to next int. You're only catching exceptions from one of them. You need to do it for both.
I'd put some thought into reorganizing this code a bit. You don't really need two calls to nextInt. You can do it with one by changing what things are in the loop and what aren't. Since you're a beginner I'll let you think about that for a bit rather than hand you the answer.

Using Scanner object for spell checking as a newbie

Scanner kb = new Scanner(System.in);
String plt;
String msr;
double wgh;
System.out.println("'Welcome to interplanetary weight calculator.");
Thread.sleep(2500);
System.out.println("");
System.out.println("Please choose one planet for calculation:");
System.out.println("1.Venus 2.Mars 3.Jupiter");
System.out.println("4.Saturn 5.Uranus 6.Neptune");
System.out.print(">");
do {
while (!kb.hasNextLine()) {
System.out.println("That's not a planet!");
kb.nextLine(); // this is important!
}
plt = kb.nextLine();
} while (plt.equalsIgnoreCase("Venus"));
System.out.println("Thank you!Now will do calculation on " + plt); }}
I want to make a weight calculator between planets and I also want a spell checker too but when I write something, it just prints out "Thank you! Now, will do the calculation on ....".
It prints out integers too. I can't find where did I do wrong.
Essentially, what happens is that your loop will run once, you can enter something and it will then exit the loop because anything except "venus" (in any combination of upper and lower case) will exit the loop. This is why it will also print numbers, etc.
The solution to this might be to add an ! to the beginning of the condition. This will invert the condition, meaning now only entering "venus" will cause the loop to exit which will result in the program continuing to run everything below the loop. However, there's still not going to be any kind of error message. Spell-checking and error handling would be achieved differently.

Why does this While loop cycle twice?

I made this while loop that is supposed to fulfill functions for different shapes and after it fulfills the function for that shape, it will keep asking for shapes until the user types "Exit". I have only done Triangles so far so I just have some filler functions to fulfill to make sure that it loops correctly. The problem is, after I'm done with triangles, it will print the menu twice before asking for an input instead of just printing once. Can anyone explain this to me?
while(password){
System.out.println();
System.out.println("---Welcome to the Shape Machine---");
System.out.println("Available Options:");
System.out.println("Circles");
System.out.println("Rectangles");
System.out.println("Triangles");
System.out.println("Exit");
String option = keyboard.nextLine();
if(option.equals("Exit")){
System.out.println("Terminating the program. Have a nice day!");
return;
} else if(option.equals("Triangles")){
System.out.println("Triangles selected. Please enter the 3 sides:");
int sideA = 0;
int sideB = 0;
int sideC = 0;
do{
sideA = keyboard.nextInt();
sideB = keyboard.nextInt();
sideC = keyboard.nextInt();
if(sideA<0 || sideB<0 || sideC<0)
System.out.println("#ERROR Negative input. Please input the 3 sides again.");
} while(sideA<0 || sideB<0 || sideC<0);
if((sideA+sideB)<=sideC || (sideB+sideC)<=sideA || (sideA+sideC)<=sideB){
System.out.println("#ERROR Triangle is not valid. Returning to menu.");
continue;
} else {
System.out.println("good job!");
}
}
}
It might be that you are using keyboard.nextLine();. In your code outside the while loop make sure that you are always using .nextLine() and nothing else.
Reasoning: If you use .next(), it'll only consume one word so the next time you call .nextLine(), it'll consume the end of that line.
After you say sideC = keyboard.nextInt() the carriage return that you typed (after typing the number) is still in the input buffer. Then you print the menu and execute String option = keyboard.nextLine(); That command reads up to and including the first newline it finds, which is the newline that is still in the buffer.
So option is now a bare newline character, which does not match "Exit" or "Triangle", so it loops again and prints th menu again.
This problem is caused by left-over characters like space, carriage-return, newline, form-feed in the input buffer.
Since the next keyboard.nextLine() doesn't match any of given options (and since there is no "else" at the bottom of while loop to deal with this case), the control goes into next iteration, prints the options again. Based on surrounding context of processing of input, there are several good answers to address this problem on SO.
Since your intention is to skip over all blanks, carriage-returns, newlines, form-feeds till you get a valid string (option) again, the following code works best in a case like yours.
System.out.println();
System.out.println("---Welcome to the Shape Machine---");
//...
System.out.println("Exit");
String option = keyboard.nextLine();
keyboard.skip("[\\s]*");

How to return to a specific line of code in java

OK so this is my first post here. (Be kind to me :)) I'm like two weeks old to java and wanted to create an app that can do the jobs of a total, average and average grader.
My question here is. How can I return to a specific line of code after one operation has ended
Eg: I want the code to runString menu1="Input the number of the operation you desire "; after the total or average has been found.
Thanks in advance
import java.util.Scanner;
public class grader
{
public static void main (String args[])
{
Scanner input=new Scanner(System.in);
System.out.println ("Input your Chemistry marks");
float a= input.nextFloat();
System.out.println ("Input your Biology marks");
float b= input.nextFloat();
System.out.println ("Input your Physics marks");
float c= input.nextFloat();
String menu1="Input the number of the operation you desire ";
String op1="1. Total ";
String op2="2. Average ";
String op3="3. Grade ";
String op4="4. Exit ";
System.out.println (menu1+op1+op2+op3+op4);
Scanner menuselect=new Scanner(System.in);
int option= input.nextInt();
float tot=(a+b+c);
float avg=((a+b+c)/3);
if (option==1)
System.out.println ("Your total is "+tot);
else if (option==2)
System.out.println ("Your average is "+avg);
else if (option==3)
if (avg<0.0)
System.out.println ("Please input proper data");
else if (avg<=49.9)
System.out.println ("Fail");
else if (avg<=69.9)
System.out.println ("Pass");
else if (avg<=100.0)
System.out.println ("Excellent");
else
System.out.println ("Please input proper data");
}
}
You should use the do-while loop. How it works is it executes some code, checks to see if a condition evaluates to true, and if so, executes the code again.
do {
//your code here
}
while (/*some condition*/);
Usually when you want to repeat one or more lines of code, you do so using a loop. In general, a loop is set up like this:
while(loopGuard){
//code to repeat
}
Where loopGuard is some boolean statement that gets updated inside your loop. The code inside the loop will continue executing until your loopGuard statement is no longer true.
In your case, you may want to loop until the user presses a certain button, until it has run a certain number of times, or any other arbitrary reason you have chosen. The main thing to remember is to make sure that your loop guard will eventually become false, otherwise you'll find yourself in an infinite loop.
In your case you should use a while loop with the usage of continue and break. A second option, you can use a labeled break statement (explained here).
Btw, in java language there a goto keyword. But it's not implemented (or removed). Read here for more details.
I would suggest a do - while loop . A do while loop runs at least once , which is necessary as you're program needs to be run at least once . Put all the statements from Input the operation number to the calculating statements under do while loop . It should work out just fine .

While loop issue in Java

This is a little bit of my code.
System.out.print("Would you like to continue (Y/N)?");
while (!Anwser.equals("Y")){
Anwser = UserInput.next();
System.out.println("Would you like to continue (Y/N)?");
}
This is the answer.
> Would you like to continue (Y/N)?
> Would you like to continue (Y/N)?
Why does it print it out again although I typed Y and the conditions were not met? After this it continues with the code:
A while loop is done zero or more times.
A do while loop is done one or more times.
For a continuation question you do not really care what the user inputs as long as it is a 'Y' or 'y'.
Anything else will terminate the program.
Also with a continuation question the program usually wants to run once. So wrap your code in a do while loop.
do {
// Your code goes here
System.out.print("Would you like to continue (Y/N)?");
Anwser = UserInput.next();
} while (answer.equalsIgnoreCase( "Y"));
As to why your code does not work. Perhaps you should have assigned a value to Answer before the loop starts.
Try changing the value of "Anwser" variable and replace it with the user's input
like this:
System.out.print("Would you like to continue (Y/N)?");
Anwser = UserInput.next();
while (!Anwser.equals("Y")){
System.out.println("Would you like to continue (Y/N)?");
Anwser = UserInput.next();
}
The reason why it is printing twice is because the first line is printing the question outside of the loop, then tests the answer (which was not captured and then relies on what the reference variable was initialized to) then enters the while loop which first gets the input from the user to the last question then prints the question again.
System.out.print("Would you like to continue (Y/N)?"); //prints to screen
//no input captured before test
while (!Anwser.equals("Y")){ //tests the reference variable
Anwser = UserInput.next(); //captures user input after test
System.out.println("Would you like to continue (Y/N)?"); //asks question again
}
The while loop is a a pre-test loop, meaning that it tests the condition before running the code inside. With this code, you're testing the response to the first question to answer the second. So, all you would really need to do if you wanted to keep the while loop is put the question once inside the loop and like so:
while (!Anwser.equalsIgnoreCase("Y"))
{
System.out.println("Would you like to continue (Y/N)?");
Anwser = UserInput.next();
}
Also, since you're just capturing a character, maybe instead of making a String object to hold a character literal, try a char variable. Here is that solution:
char answer = ' ';
Scanner userInput = new Scanner(System.in);
while (answer != 'N') // check for N to end
{
System.out.println("Would you like to continue (Y/N)?");
answer = Character.toUpperCase(userInput.nextLine().charAt(0));
}

Categories