Java - How to quit a While Loop mid loop - java

I'm trying to make a program that asks an electrician to enter a number in Volts. If he/she enters a value either bigger than 20 or less than 0, the program should end without prompting the user to go again. Right now, I have it so it prompts the user to quit or continue, which I don't want. Here's the guts of the program:
public static void main(String[] args) {
Scanner kbReader = new Scanner(System.in);
String input = "";
int voltage;
boolean Loop = true;
while (Loop) {
System.out.print("Enter a numeric value of 0 to 20 volts");
input = kbReader.nextLine();
voltage = Integer.parseInt(input);
if (voltage < 0 || voltage > 20) {
System.out.println("Invalid input.");
}
else if (voltage >= 0 && voltage < 5) {
System.out.println("Insufficient Voltage - Replace Relay");
}
else if (voltage >= 5 && voltage < 15) {
System.out.println("Low Voltage");
}
else if (voltage >= 15 && voltage < 18) {
System.out.println("Voltage is in proper range");
}
else if (voltage >= 18 && voltage <= 20) {
System.out.println("Voltage is high - Check Transformer");
}
System.out.print("\n\nType \"Q\" to quit, or type nothing to go again.");
input = kbReader.nextLine();
if (input.equalsIgnoreCase("q")) {
Loop = false;
}
}
}
The indentation seems to be a bit off. I'm not too sure how to fix that.

All you need to do is
if (voltage < 0 || voltage > 20) {
System.out.println("Invalid input.");
break;
}

You can use a break in that first if clause :
if (voltage < 0 || voltage > 20)
{
break;
}

You can try using a break;. Breaks allows the while loop to exit.

Related

How to make a number invalid

Create a new program called minusSentinel2.
Prompt the user to enter whole numbers between 1 and 100. Allow the user to enter as many numbers as desired.
If an invalid number is entered, print "Invalid entry." Prompt the user again until a valid number is entered.
Once -1 is entered, the program stops and prints the largest number entered with the text "The largest number entered is: "
I am having some trouble on the "Invalid entry." part. When I type a number greater than 100, "Invalid entry." does not get printed. How do I fix this? Thank you!
import java.util.*;
public class minusSentinel2
{
public static void main (String[] args)
{
Scanner console = new Scanner(System.in);
System.out.println("Enter a number between 1-100 (type -1 to quit):");
int number = console.nextInt();
int max = number;
if (number < 1 && number > 100)//chekcs if value is valid
{
System.out.println("Invalid entry.");
System.out.println("Enter a number between 1-100 (type -1 to quit).");
console.next();
}
while (number != -1)
{
number = console.nextInt();
if (number > max)
{
max = number;
}
}
System.out.print("The largest number entered is: " + max);
}
}
Firstly, I suggest you to don't copy and paste what we ask you to do, and just reformulates with only necessary parts for us.
For your issue, this condition is wrong:
if (number < 1 && number > 100)
It correspond to "lower than 1 and bigger than 100".
So, instead of && (and) operator, use || (or) operator like that :
if (number < 1 || number > 100) {
// it's not valid because lower than 1 or greater than 100
}
Finally, what you are doing seems to have another issue.
If you enter an invalid number, it will ask again only one time, and not same the new value. So, I suggest you to use while loop like that :
int number = 0;
while(number < 1 || number > 100) {
number = console.nextInt();
if (number < 1 || number > 100) {
System.out.println("Invalid entry.");
System.out.println("Enter a number between 1-100 (type -1 to quit).");
}
}
int max = number;
To conclude, this is the full code:
Scanner console = new Scanner(System.in); // create scanner
int number = 0; // create new variable that will be used outside of while loop
while (number < 1 || number > 100) { // while the number isn't valid
System.out.println("Enter a number between 1-100 (type -1 to quit):");
number = console.nextInt(); // wait for user input
if (number == -1) { // stop program
console.close();
return;
} else if (number < 1 || number > 100) { // number invalid
System.out.println("Invalid entry.");
}
}
System.out.println("Now enter all number that you want. End with -1.");
int max = number; // create new max value
while (number != -1) {
number = console.nextInt();
if (number < 1 || number > 100) { // number invalid
System.out.println("Invalid entry.");
} else if (number > max) { // if number is upper than current one
max = number;
// here you can do something like that:
// System.out.println("New max value: " + max);
} else {
// the value is value but not upper than current one, so we can write:
// System.out.println("This value isn't upper to " + max);
}
}
System.out.print("The largest number entered is: " + max);
console.close();

Java while loop until conditions are met

Trying to make the user keep inputting correct integers between 2 sets of values, but for example if the user inputs a wrong integer, then the while loop skips and runs onto the next code in my program. If anyone could point out how I can make the user repeat the question at each step if they get it wrong, would appreciate it.
System.out.print("How many asteroids: ");
int asteroid = input.nextInt();
while (asteroid > 0) {
System.out.print("x location of the asteroid (between 1-950 pixels): ");
double asteroidLocationX = input.nextDouble();
if (asteroidLocationX >= 1 && asteroidLocationX <= 950) {
System.out.print("y location of the asteroid (between 150-550 pixels): ");
double asteroidLocationY = input.nextDouble();
if (asteroidLocationY >= 150 && asteroidLocationY <= 550) {
System.out.print("Width of the asteroid (min: 30 pixels, max: 50 pixels): ");
double asteroidSizeWidth = input.nextDouble();
if (asteroidSizeWidth >= 30 && asteroidSizeWidth <= 50) {
System.out.print("Height of the asteroid (min: 30 pixels, max: 50 pixels): ");
double asteroidSizeHeight = input.nextDouble();
if (asteroidSizeHeight >= 30 && asteroidSizeHeight <= 50) {
gc.setFill(Color.ALICEBLUE);
gc.fillOval(asteroidLocationX, asteroidLocationY, asteroidSizeWidth, asteroidSizeHeight);
} else
System.out.println("Wrong input, try again");
} else
System.out.println("Wrong input, try again");
}else
System.out.println("Wrong input, try again");
} else
System.out.println("Wrong input, try again");
asteroid--;
}
You need to re-ask the question if there's a problem with the answer
double val = -1;
do {
System.out.println("Enter a number between 1 and 10");
val = input.nextDouble();
while (input >= 1 && input <= 10);

Number guess rounds

i wanted to do the guess the number game. For one round my programm works and I can guess a number. I want that the user can enter the amout of rounds (1-20) what he wants to play, but there is my problem this isn't working as thought. I tried to use a boolean but after I guessed the number for 1 round it doesn't begin the next round.
The In function is similar to scanner, but I have a java class for that therefore I use that.
public class GuessNumber {
public static void main(String[] args) {
System.out.println("round 1-20");
int roundTyped = In.readInt();
int rndN = (int) (Math.random()*100)+1;
int typedN = 0;
int trys = 0;
boolean active = true;
int round = 0;
while (active) {
while (typedN != rndN) {
trys++;
System.out.println(trys + ". Versuch:");
typedN = In.readInt();
if(typedN < 1 || typedN > 100) {
System.out.println("ungueltig");
}else if(typedN < rndN) {
System.out.println("groesser");
}else if(typedN > rndN) {
System.out.println("kleiner");
}else if(typedN == rndN) {
System.out.println("korrrekt");
}
}
round++;
if (round == roundTyped) {
active = false;
}
}
}
You set the number to be guessed only once at the start of the program. Therefore, after the user has guessed the correct number once, the remaining rounds will all be completed instantly (the condition of the inner while will always be true).
I would suggest you use a debugger to find problems like these. When you step through your program, it will immediately become obvious what is happening.
Having two while loops is unnecessary, you can put several conditions for the while, and you use 2 variables that will be the same round and trys.
But your biggest problem is that you actually set your active to false right before checking if it is true.
Try something like that :)
System.out.println("round 1-20");
int roundTyped = In.readInt();
int rndN = (int) (Math.random()*100)+1;
int typedN = 0;
int nTrysAllowed = 10; // The max number of tries
int trys = 0;
int round = 0;
while (round < roundTyped) {
while (typedN != rndN && trys < nTrysAllowed) {
trys++;
System.out.println(trys + ". Versuch:");
typedN = In.readInt();
if(typedN<1 || typedN >100) {
System.out.println("ungueltig");
} else if(typedN < rndN) {
System.out.println("groesser");
} else if(typedN > rndN) {
System.out.println("kleiner");
} else {
System.out.println("korrrekt");
}
}
// Here you can reduce the max number of tries for example or do whatever you want. For example:
round++;
if (typedN == rndN) {
// New number to guess
rndN = (int) (Math.random()*100)+1;
// Difficulty
nTrysAllowed--;
trys = 0;
} else {
System.out.println("Game done you can't go to next round, you lose this one.");
round = roundTyped;
}
}

How should I write this code?

again:
while (!s.hasNextInt()) s.next();
amount = s.nextInt();
if(amount < 0 || amount > numberOfCards) {
System.out.println("You need to enter a number between 0 and "+numberOfCards);
goto again;
}
It works fine in C# but in Java there is no goto. I can think of large complex ways of redoing this but I was interested in what is the cleanest most recommended way to write this code.
Stupid way:
while (true) {
while (!s.hasNextInt()) s.next();
amount = s.nextInt();
if(amount < 0 || amount > numberOfCards) {
System.out.println("You need to enter a number between 0 and "+numberOfCards);
} else {
break;
}
}
Wrap it in a loop :
while (amount < 0 || amount > numberOfCards) {
while (!s.hasNextInt()) s.next();
amount = s.nextInt();
if(amount < 0 || amount > numberOfCards) {
System.out.println("You need to enter a number between 0 and "+numberOfCards);
}
}

Loop user input until conditions met

I need to ask the user to input a number to be used as the start of a range, and then input another number that is the end of the range. The start number has to be 0 or greater and the end number cannot be larger than 1000. Both numbers must be divisible by 10. I have found a way to meet these conditions, however if they are not met my program just tells the user that their input was incorrect. Is it possible for me to code it so that after the user inputs it will check to make sure the conditions are met, and if they are not loop back and make them input again. Here is the code I have so far.
Scanner keyboard = new Scanner(System.in);
int startr;
int endr;
System.out.println("Enter the Starting Number of the Range: ");
startr=keyboard.nextInt();
if(startr%10==0&&startr>=0){
System.out.println("Enter the Ending Number of the Range: ");
endr=keyboard.nextInt();
if(endr%10==0&&endr<=1000){
}else{
System.out.println("Numbers is not divisible by 10");
}
}else{
System.out.println("Numbers is not divisible by 10");
}
Easy with do-while:
Scanner keyboard = new Scanner(System.in);
int startr, endr;
boolean good = false;
do
{
System.out.println("Enter the Starting Number of the Range: ");
startr = keyboard.nextInt();
if(startr % 10 == 0 && startr >= 0)
good = true;
else
System.out.println("Numbers is not divisible by 10");
}
while (!good);
good = false;
do
{
System.out.println("Enter the Ending Number of the Range: ");
endr = keyboard.nextInt();
if(endr % 10 == 0 && endr <= 1000)
good = true;
else
System.out.println("Numbers is not divisible by 10");
}
while (!good);
// do stuff
You need to use a while, something like:
while conditionsMet is false
// gather input and verify
if user input valid then
conditionsMet = true;
end loop
should do it.
The all-purpose procedure is:
Read the input in an infinite loop.
Use a break; statement to exit the loop when the conditions are met.
Example:
Scanner keyboard = new Scanner(System.in);
int startr, endr;
for (;;) {
System.out.println("Enter the starting number of the range: ");
startr = keyboard.nextInt();
if (startr >= 0 && startr % 10 == 0) break;
System.out.println("Number must be >= 0 and divisible by 10.");
}
for (;;) {
System.out.println("Enter the ending number of the range: ");
endr = keyboard.nextInt();
if (endr <= 1000 && endr % 10 == 0) break;
System.out.println("Number must be <= 1000 and divisible by 10.");
}
If after invalid input you want to display just the error message without repeating the initial prompt message, move the initial prompt message just above/outside the loop.
If you do not have need for the separate error message, you can re-arrange the code to use a do-while loop to check the conditions, which is just a little shorter:
Scanner keyboard = new Scanner(System.in);
int startr, endr;
do {
System.out.println("Enter the starting number of the range.");
System.out.println("Number must be >= 0 and divisible by 10: ");
startr = keyboard.nextInt();
} while (!(startr >= 0 && startr % 10 == 0));
do {
System.out.println("Enter the ending number of the range.");
System.out.println("Number must be <= 1000 and divisible by 10: ");
endr = keyboard.nextInt();
} while (!(endr <= 1000 && endr % 10 == 0));

Categories