Java while loop until conditions are met - java

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);

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();

Trying to find the best way to re-access code

I'm creating a gambling application with 2 games. However I want to be able to switch from one game to the next. I tried if(game == 1), but it seemed that once I matched the condition, it exited the loop and trying to take input again would not switch to the second game. Then I tried do while but even when I set my input to "2" it still starts game #1. Any suggestions on what I should do?
import java.util.Scanner;
import java.util.Random;
public class Project2 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int min = 1;
int max = 10;
int colmax = 2;
double balance = 2500;
double bet1 = 0;
double bet2 = 0;
String kBet = null;
//Call method gameChoice to allow player to choose what game they want to play.
gameChoice();
int game = input.nextInt();
do {
System.out.println("-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-BLACK JACK-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-");
System.out.print("Please choose Black or Red, and a number from 1-10..(Example: Red 4): ");
String color = input.next();
int number = input.nextInt();
//Seperate bets for color and number. Bet1 = color bet, bet2 = number bet
System.out.print("Your available balance is $"+balance+". How much would you like to bet on "+color+"?");
bet1 = input.nextInt();
if(bet1 > balance) {
System.out.print("You dont have enough money to bet $"+bet1+". Please enter a valid bet: $");
bet1 = input.nextInt();
}
else
balance -= bet1;
double profit1 = (bet1 * 2) - bet1;
//Bet 2 for number.
System.out.print("Your available balance is $"+balance+". How much would you like to bet on "+number+"?");
bet2 = input.nextInt();
if(bet2 > balance) {
System.out.print("You dont have enough money to bet $"+bet2+". Please enter a valid bet: $");
bet2 = input.nextInt();
}
else
balance -= bet2;
double profit2 = (bet2 * 5) - bet2;
//Give bet info
System.out.println("------------------------------BET INFO------------------------------------");
System.out.println("You just bet $"+bet1+" on "+color+" and $"+bet2+" on number "+number);
System.out.println("Spinning............");
System.out.println("------------------------------RESULTS-------------------------------------");
//Generate random number, Generate random color.
Random rouletteNum = new Random();
int rNum = min + rouletteNum.nextInt(max);
int rCol = min + rouletteNum.nextInt(colmax);
//Only generate 2 numbers between 1-2; 1 is black, 2 is red.
if (rCol == 1) {
System.out.println("The machine landed on Black "+rNum);
}
else if(rCol != 1) {
System.out.println("The machine landed on Red "+rNum);
}
//All possible conditions for betting outcomes.
if(rNum == number) {
System.out.println("Congrats, you guessed the right number! You've won $"+profit2);
balance += (bet2 * 5);
}
else if(rNum != number) {
System.out.println("Sorry!You didnt guess the right number! You've lost $"+bet2);
}
if(rCol == 1 && color.equals("Black")) {
System.out.println("Congrats, you guessed the right color! You've won $"+profit1);
balance += bet1 * 2 - bet1;
}
else if(rCol == 2 && color.equals("Red")) {
System.out.println("Congrats, you guessed the right color! You've won $"+profit1);
balance += bet1 * 2 - bet1;
}
if(rCol == 2 && color.equals("Black")) {
System.out.println("Sorry, you didn't guess the right color. You've lost $"+bet1);
}
else if(rCol == 1 && color.equals("Red")) {
System.out.println("Sorry, you didn't guess the right color. You've lost $"+bet1);
}
System.out.println("------------------------------------------------------------------------");
//Call isBroke method to check if player is bankrupt.
if(isBroke(balance) == true) {
endGame(balance);
}
else {
//If player isn't bankrupt, ask if they want to place another bet.
System.out.println("New balance: $"+balance);
gameChoice2();
game = input.nextInt();
}
}
while(game == 1);
{
do {
int bet = 0;
double start = 1.00;
double crashValue = 1.00;
int stopGame = 1;
double cashout = 0;
System.out.println("-------------------CRASH GAME--------------------------");
System.out.println("Welcome to Crash!");
System.out.print("What number would you like to cashout at?(Ex. 1.15):");
cashout = input.nextDouble();
System.out.print("Your balance is $"+balance+". How much would you like to bet on this round?:");
bet = input.nextInt();
//check if bet amount is greater then the balance.
if(bet > balance) {
System.out.print("You dont have enough money to bet $"+bet+". Please enter a valid bet: $");
bet = input.nextInt();
}
else
System.out.println("--------------------------------------------------------------------------");
System.out.println("Round is beginning.........");
for(int i =0; i < stopGame; i++) {
//Do while to keep the numbers generating until i == 1 (until crash)
do {
//Generate random number from 1-100, if the number is less than 98, print the digit (Example : 1.34)
int crash =(int)(Math.random() * 100);
if (crash < 98) {
start += .01;
System.out.printf("%.2f\n",start);
}
//if random number from 1-100 is greater than 98, crash the game.
else if(crash > 98) {
i++;
crashValue = start;
System.out.println("----------------------------RESULTS--------------------------------");
System.out.print("CRASH! The game crashed at ");
System.out.printf("%.2f",start);
System.out.println("x");
}
}
while(i == 0);
}
//Check if player cashed out before game crashed.
if(cashout < crashValue) {
System.out.println("Congrats! You cashed out at "+cashout+" before the game crashed. You've won $"+bet*cashout);
balance += bet * cashout;
}
//Player didn't cash out in time, and lost.
else {
System.out.println("Sorry! The game crashed before you could cash out. You've lost $"+bet);
balance -= bet;
}
System.out.println("------------------------------------------------------------------------");
//check if player is bankrupt.
if(isBroke(balance) == true) {
endGame(balance);
}
else {
//If they arent bankrupt, ask if they want another bet.
System.out.println("New balance: $"+balance);
gameChoice2();
game = input.nextInt();
}
}
while(game == 2);
}
You've used a do...while loop. This type of loop always executes its body at least once before evaluating the while condition.

how to prompting the user to enter a correct value after he already entered a wrong(out of range) value?

System.out.println("Enter the first test score:");
double test1 = input.nextInt();
if (!(test1 >= 0 && test1 <= 100))
System.out.println("This is out of the acceptable range, please enter a number between 0 and 100 .");
System.out.println("Enter the second test score:");
double test2 = input.nextInt();
if (!(test2 >= 0 && test2 <= 100))
System.out.println("This is out of the acceptable range, please enter a number between 0 and 100 .");
If i prompt the user to enter a value for test1 and its nor in the specific range, how do i prompt him again to enter a correct value ?. now if i run the and enter a bad value the "This is out of the acceptable range, please enter a number between 0 and 100 " msg would show up but it goes straight to test2. i tried to do this
System.out.println("Enter the first test score:");
double test1 = input.nextInt();
if (!(test1 >= 0 && test1 <= 100))
System.out.println("This is out of the acceptable range, please enter a number between 0 and 100 .");
double test1 = input.nextInt();
but i get an error msg.
Do i have to use a loop and if so how?
That's because you are declaring test1 twice.
double test1 = input.nextInt();
if (!(test1 >= 0 && test1 <= 100))
System.out.println("This is out of the acceptable range, please enter a number between 0 and 100 .");
--> double test1 = input.nextInt(); //Look at this line
Just try following:
double test1 = input.nextInt();
if (!(test1 >= 0 && test1 <= 100))
System.out.println("This is out of the acceptable range, please enter a number between 0 and 100 .");
test1 = input.nextInt();
For even cleaner code use following method:
public double getValue(){
double test1=input.nextInt();
if (!(test1 >= 0 && test1 <= 100)){
return getValue();
}else{
return test1;
}
}
Above code would keep taking user inputs unless the input is correct according to !(test1 >= 0 && test1 <= 100) condition.
First, you are declaring test1 twice, second - you can use loop
double test1 = input.nextInt();
while(!(test1 >= 0 && test1 <= 100))
{
System.out.println("This is out of the acceptable range, please enter a number between 0 and 100 .");
/*double */test1 = input.nextInt();
}
try something like
double test1 = input.nextInt();
while(!(test1 >= 0 && test1 <= 100)) {
System.out.println("Enter a valid number");
test1.nextInt();
}
The idea is to prompt the user until he enters a valid input. If you use simple if-statements or a fixed for-loop you'll end up asking only for a fixed amount for the right value.
Another thing you should keep in mind is:
if (!(test1 >= 0 && test1 <= 100))
System.out.println("This is out of the acceptable range, please enter a number between 0 and 100 .");
double test1 = input.nextInt(); //There is no need to declare test1 again. Remove double
will be compiled as
if (!(test1 >= 0 && test1 <= 100))
System.out.println("This is out of the acceptable range, please enter a number between 0 and 100 .");
test1 = input.nextInt(); //This is not part of the if!!!!
so you have to use brackets like
if (!(test1 >= 0 && test1 <= 100)) {
System.out.println("This is out of the acceptable range, please enter a number between 0 and 100 .");
test1 = input.nextInt();
}

Java - How to quit a While Loop mid loop

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.

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