I am trying to validate the the user input, but I can't get it to work.
The user has to enter an amount of Revenue between 0-20,000, but not anything more than that.
In addition, the user must enter expenses between 1500-10000, but not anything more than that or less than that.
I also am trying to loop the code as well. I am asking the user if they have additional records they want to enter in or not, and I am counting how many times the record has been done.
Can anyone tell me what I am doing wrong and point me in the right direction?
Here is what I have so far:
import javax.swing.JOptionPane;
import java.io.*; // Access System.out
import java.util.Scanner;
public class RevenueScan
{
public static void main(String[] args)
{
// Declarations
Scanner in = new Scanner(System.in);
int productNumber;
float revenue;
float expenses;
double finalValue;
char repeat;
int counter = 0;
String input;
Scanner keyboard = new Scanner(System.in);
// Do Loop to run
do
{
// Pop up to advise the user the conditions that have to be met for inputs
System.out.println("Please ensure that your revenue is between 0 to 20,000.00 dollars."
+ "\nPlease ensure that your expenses are between 1,500.000 to 10,000.00 dollars.");
// Pop up to ask the user the values of the variables
System.out.println("Enter in a Product Number (or-1 to END)"
+ "\nEnter the Revenue"
+ "\nEnter the Expenses");
// Read in values
productNumber = in.nextInt();
revenue = in.nextFloat();
expenses = in.nextFloat();
//States the values entered by user
while (revenue < 0 || revenue > 20000 || expenses < 1500 || expenses > 10000);
{
System.out.println("You have entered in either an invalid revenue or expense. Please enter in valid numbers.");
{
System.out.println("Here is the product number you entered: " + productNumber + "."
+ "\nHere is the revenue you entered: " + revenue + "."
+ "\nHere are the expenses you entered: " + expenses + ".");
counter++;
//calculates final value
}
}
finalValue = revenue - expenses;
// Calculates final value and displays as net profit, loss or break even.
if (finalValue > 0)
{
System.out.println("You made a profit. Your net income is: " + finalValue);
}
else
if (finalValue == 0)
{
System.out.println("You broke even. Your revenue was " + revenue + " your expenses were " + expenses);
}
else
if (finalValue < 0)
{
System.out.println("You have not made any profit. Your net loss is: " + finalValue);
}
System.out.println("Number of records: " + counter);
//validate user input
System.out.println("Would you like to input more records?");
System.out.println("Enter 'Y' for yes or 'N' for no.");
input = keyboard.nextLine();
repeat = input.charAt(0);
}
while (repeat == 'Y' || repeat == 'y');
{
}
}
}
You have a ; after the while-statement, it shouldn't be there, otherwise the while-loop is empty, as opposed to containing the block following it.
while (revenue < 0 || revenue > 20000 || expenses < 1500 || expenses > 10000)
{
System.out.println("You have entered in either an invalid revenue or expense. Please enter in valid numbers.");
{
System.out.println("Here is the product number you entered: " + productNumber + "."
+ "\nHere is the revenue you entered: " + revenue + "."
+ "\nHere are the expenses you entered: " + expenses + ".");
counter++;
}
}
But once you fix this, the above block will just keep looping, since none of the values can change inside that loop.
Also, those inner brackets {} are somewhat pointless.
I recommend this:
if (revenue < 0 || revenue > 20000 || expenses < 1500 || expenses > 10000)
{
System.out.println("You have entered in either an invalid revenue or expense. Please enter in valid numbers.");
System.out.println("Here is the product number you entered: " + productNumber + "."
+ "\nHere is the revenue you entered: " + revenue + "."
+ "\nHere are the expenses you entered: " + expenses + ".");
counter++;
continue; // go to the start of the do-while loop
}
Then you also have to change:
char repeat;
to:
char repeat = 'Y';
otherwise it doesn't compile since continue still triggers the condition check, and repeat won't be initialized the first time, and Java doesn't allow this.
If you want to stick to a while-loop, put something like these lines in there:
// tell user to input values again
System.out.println("Enter in a Product Number (or-1 to END)"
+ "\nEnter the Revenue"
+ "\nEnter the Expenses");
// read in values
productNumber = in.nextInt();
revenue = in.nextFloat();
expenses = in.nextFloat();
This will allow the user to input new values until the conditions are met.
And the format of a do-while loop is:
do { ... }
while (...);
Not:
do { ... }
while (...) { ... }
So change:
while (repeat == 'Y' || repeat == 'y');
{
}
To:
while (repeat == 'Y' || repeat == 'y');
Related
I am a new coder. Working on an assignment. This is also my first post here so I apologize if it's a little sloppy.
I'm having some troubles with my if/else statements in Java...the "if" conditions seem to work okay. But my "else" conditions do not. Take a look at the code and the build results below.
Basically, I enter an ingredient. And then I put in the number of cups needed. And the number of calories the ingredient has per x cup. That all seems to work as long as I input what I want to for "successful" results.
Successful Build Image
But when I start to input values outside of my criteria, my application doesn't seem to care. If I input 0, I should get that output of "your response is invalid" or whatever it is I coded. But it just seems to skip over that entirely.
Bad Code Image
package recipe_collection_manager;
import java.util.Scanner;
public class Ingredient {
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
//Initializes the variables
String nameOfIngredient = "";
int numberCups = 0;
int numberCaloriesPerCup = 0;
int totalCaloriesPerCup = 0;
double totalCalories = 0.0;
// Enter the name of the ingredient.
System.out.println("Please enter the name of the ingredient: ");
nameOfIngredient = scnr.next();
// Enter the number of cups needed for the ingredient.
// If Else statements used to establish if the number of cups is valid.
System.out.println("Please enter the number of cups of "
+ nameOfIngredient + " we'll need. The number of cups must be between 1 and 100: ");
numberCups = scnr.nextInt();
if (numberCups >= 1 || numberCups <= 100) {
System.out.println("The number of cups is valid.");
} else if (numberCups <= 1 || numberCups >= 100) {
System.out.println("The number you have entered is invalid. Please try again.");
}
// Enter the number of calories used per cup.
// If Else statements are used to establish if the number of calories is valid.
System.out.println("Please enter the number of calories per cup: ");
numberCaloriesPerCup = scnr.nextInt();
if (numberCaloriesPerCup >= 1 || numberCaloriesPerCup <= 1000) {
System.out.println("The number of calories is valid.");
} else if (numberCaloriesPerCup <= 1 || numberCaloriesPerCup >= 1000) {
System.out.println("The number you have entered is invalid. Please try again.");
}
// Calculation for totalCalories based on numberCups and numberCaloriesPerCup
if (numberCups > 0 && numberCaloriesPerCup > 0) {
totalCalories = numberCups * numberCaloriesPerCup;
}
System.out.println(nameOfIngredient + " uses " + numberCups
+ " cups and has " + totalCalories + " calories.");
}
}
Problem was in line:
if (numberCups >= 1 || numberCups <= 100) {
...
}
When you entered 0, program checked if 0 is greater or equal to 1, and that was false but you had also "or" condition ( || ), and in that condition you were checking if 0 <= 100 and because that is true, false || true gives true and that's why your if statement was correct. You needed to use "and" ( && ) instead of "or". There was flaw in your logic.
Test code below, it should work now:
package recipe_collection_manager;
import java.util.Scanner;
public class Ingredient {
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
//Initializes the variables
String nameOfIngredient = "";
int numberCups = 0;
int numberCaloriesPerCup = 0;
int totalCaloriesPerCup = 0;
double totalCalories = 0.0;
// Enter the name of the ingredient.
System.out.println("Please enter the name of the ingredient: ");
nameOfIngredient = scnr.next();
// Enter the number of cups needed for the ingredient.
// If Else statements used to establish if the number of cups is valid.
System.out.println("Please enter the number of cups of "
+ nameOfIngredient + " we'll need. The number of cups must be between 1 and 100: ");
numberCups = scnr.nextInt();
if (numberCups >= 1 && numberCups <= 100) {
System.out.println("The number of cups is valid.");
} else if (numberCups <= 1 || numberCups >= 100) {
System.out.println("The number you have entered is invalid. Please try again.");
}
// Enter the number of calories used per cup.
// If Else statements are used to establish if the number of calories is valid.
System.out.println("Please enter the number of calories per cup: ");
numberCaloriesPerCup = scnr.nextInt();
if (numberCaloriesPerCup >= 1 || numberCaloriesPerCup <= 1000) {
System.out.println("The number of calories is valid.");
} else if (numberCaloriesPerCup <= 1 || numberCaloriesPerCup >= 1000) {
System.out.println("The number you have entered is invalid. Please try again.");
}
// Calculation for totalCalories based on numberCups and numberCaloriesPerCup
if (numberCups > 0 && numberCaloriesPerCup > 0) {
totalCalories = numberCups * numberCaloriesPerCup;
}
System.out.println(nameOfIngredient + " uses " + numberCups
+ " cups and has " + totalCalories + " calories.");
}
}
Just to clarify. The following statement
if(numberCups >= 1 || numberCups <= 100) {
...
}
Is true any number of cups. Any number of cups >= 1 will be caught by the first condition. Any number of cups <= 0 will be caught by the second condition since in that case they will all be less than 100. With a logical || only one condition is required to be true for the statement to be true.
In fact,
if(numberOfCups is >= A || numberOfCups <= B) {
...
}
will always be true as long as B >= A-1.
Here I am once again. I have listened to all the previous suggestions, but because my course hasn't taught me about methods I'm wary of using one. The program should prompt the user to enter a number and a maximum number of guesses, generate a random number, have the user exhaust all the guesses or guess the correct number, then ask whether the user wants to play again. I noticed three errors and if you could help identify their solutions I will be extremely grateful:
If I enter a negative number twice in the guesses does not produce anything (I’m assuming a runtime error), same goes for if I enter 0 twice in the guesses.
After the second round of the game it doesn’t ask the user whether they would like to play again.
It is inconsistent when recognizing when the maximum number of guesses is greater than the total possible amount of numbers. i.e. If I enter 1 for guess and 1 for upper limit, this shouldn’t display the message that I should “challenge” myself, because 0 and 1 are two possible numbers being generated, greater than 1, because 2 yet it still displays that.
import java.util.Scanner;
import java.util.Random;
public class MyClass {
public static void main(String args[]) {
Scanner input = new Scanner(System.in);
System.out.println("Hello! Here are the rules for this game:");
System.out.println("1. You choose the limit of the secret number!");
System.out.println("2. I generate the secret number!");
System.out.println("3. You choose the maximum number of guesses!");
System.out
.println("4. You try to guess the secret number I generated within the number of guesses you entered!");
System.out.println("5. You may win a prize!");
System.out.println(
"With that being said, would you like to play? If yes please enter true, if not please enter false.");
boolean wantToPlay = input.nextBoolean();
while (wantToPlay != true) {
System.out.println("Thank you and remember to wash your hands! You may close me.");
System.out.println(
"Did you accidentally press false? If yes please enter true, if not you may leave the program. ");
wantToPlay = input.nextBoolean();
}
System.out.println(
"Please enter the limit of the secret number. Please note it must be a greater than 0 positive integer.");
System.out.println("Please note that your secret number will be between zero and the number you just entered.");
int upperBound = input.nextInt();
System.out.println("The upper bound you entered is" + " " + upperBound + "." + " "
+ "Is that correct? If yes please enter true, if not please enter false.");
boolean yesOrNo = input.nextBoolean();
if (upperBound <= 0) {
yesOrNo = false;
}
while (yesOrNo != true) {
System.out.println(
"Please enter the new upper bound of the secret number. Remember it must be a greater than 0 positive integer.");
upperBound = input.nextInt();
System.out.println("The upper bound you entered is" + " " + upperBound + "." + " "
+ "Is that correct? If yes please enter true, if not please enter false. ");
yesOrNo = input.nextBoolean();
if (upperBound <= 0) {
yesOrNo = false;
}
}
int secretNumber = (int) (Math.random() * upperBound);
System.out.println(
"Please enter the maximum number of guesses. Please note it must be a greater than 0 positive integer.");
int numberOfGuesses = input.nextInt();
if (numberOfGuesses >= ++secretNumber) {
System.out.println(
"Please note that the number of guesses you entered is equal or greater than the possible number of values for the secret number.");
System.out.println("If you would like more of a challenge please re-enter the number of guesses below.");
}
System.out.println("The number of guesses you entered is" + " " + numberOfGuesses + "." + " "
+ "Is that correct? If yes please enter true, if not please enter false.");
boolean yesOrNo2 = input.nextBoolean();
if (numberOfGuesses <= 0) {
yesOrNo2 = false;
}
while (yesOrNo2 != true) {
System.out.println(
"Please enter the new number of guesses. Remember it must be a greater than 0 positive integer.");
numberOfGuesses = input.nextInt();
if (numberOfGuesses >= ++secretNumber) {
System.out.println(
"Please note that the number of guesses you entered is equal or greater than the possible number of values for the secret number.");
System.out
.println("If you would like more of a challenge please re-enter the number of guesses below.");
System.out.println(
"If not you can still continue with your previous number as long as you re-enter it below.");
}
numberOfGuesses = input.nextInt();
System.out.println("The number of guesses you entered is" + " " + numberOfGuesses + "." + " "
+ "Is that correct? If yes please enter true, if not please enter false. ");
yesOrNo2 = input.nextBoolean();
if (numberOfGuesses <= 0) {
yesOrNo2 = false;
}
}
boolean loop = false;
for (int i = 0; i < numberOfGuesses; ++i) {
System.out.println("Please enter your guess.");
int guesses = input.nextInt();
if (guesses > secretNumber) {
System.out.println("Your guess is too high.");
}
if (guesses < secretNumber) {
System.out.println("Your guess is too low.");
}
if (guesses == secretNumber) {
System.out.println("Your guess is correct.");
System.out.println("Congragulations you won the game.");
loop = true;
break;
}
}
if (loop == false) {
System.out.println("Sorry you lost the game.");
System.out.println(
"Would you like to see the secret number? If so please enter true, if not please enter false");
boolean seeSecretNumber = input.nextBoolean();
if (seeSecretNumber == true) {
System.out.println("The secret number was " + secretNumber);
}
}
System.out.println("Would you like to play again? If so, please enter true, if not you may enter no.");
boolean playAgain = input.nextBoolean();
while (playAgain == true) {
System.out.println(
"Please enter the limit of the secret number. Please note it must be a greater than 0 positive integer.");
System.out.println(
"Please note that your secret number will be between zero and the number you just entered.");
upperBound = input.nextInt();
System.out.println("The upper bound you entered is" + " " + upperBound + "." + " "
+ "Is that correct? If yes please enter true, if not please enter false.");
yesOrNo = input.nextBoolean();
if (upperBound <= 0) {
yesOrNo = false;
}
while (yesOrNo != true) {
System.out.println(
"Please enter the new upper bound of the secret number. Remember it must be a greater than 0 positive integer.");
upperBound = input.nextInt();
System.out.println("The upper bound you entered is" + " " + upperBound + "." + " "
+ "Is that correct? If yes please enter true, if not please enter false. ");
yesOrNo = input.nextBoolean();
if (upperBound <= 0) {
yesOrNo = false;
}
}
secretNumber = (int) (Math.random() * upperBound);
System.out.println(
"Please enter the maximum number of guesses. Please note it must be a greater than 0 positive integer.");
numberOfGuesses = input.nextInt();
if (numberOfGuesses >= ++secretNumber) {
System.out.println(
"Please note that the number of guesses you entered is equal or greater than the possible number of values for the secret number.");
System.out
.println("If you would like more of a challenge please re-enter the number of guesses below.");
}
System.out.println("The number of guesses you entered is" + " " + numberOfGuesses + "." + " "
+ "Is that correct? If yes please enter true, if not please enter false.");
yesOrNo2 = input.nextBoolean();
if (numberOfGuesses <= 0) {
yesOrNo2 = false;
}
while (yesOrNo2 != true) {
System.out.println(
"Please enter the new number of guesses. Remember it must be a greater than 0 positive integer.");
numberOfGuesses = input.nextInt();
if (numberOfGuesses >= ++secretNumber) {
System.out.println(
"Please note that the number of guesses you entered is equal or greater than the possible number of values for the secret number.");
System.out.println(
"If you would like more of a challenge please re-enter the number of guesses below.");
System.out.println(
"If not you can still continue with your previous number as long as you re-enter it below.");
}
numberOfGuesses = input.nextInt();
System.out.println("The number of guesses you entered is" + " " + numberOfGuesses + "." + " "
+ "Is that correct? If yes please enter true, if not please enter false. ");
yesOrNo2 = input.nextBoolean();
if (numberOfGuesses <= 0) {
yesOrNo2 = false;
}
}
loop = false;
for (int i = 0; i < numberOfGuesses; ++i) {
System.out.println("Please enter your guess.");
int guesses = input.nextInt();
if (guesses > secretNumber) {
System.out.println("Your guess is too high.");
}
if (guesses < secretNumber) {
System.out.println("Your guess is too low.");
}
if (guesses == secretNumber) {
System.out.println("Your guess is correct.");
System.out.println("Congragulations you won the game.");
loop = true;
break;
}
}
if (loop == false) {
System.out.println("Sorry you lost the game.");
System.out.println(
"Would you like to see the secret number? If so please enter true, if not please enter false");
boolean seeSecretNumber = input.nextBoolean();
if (seeSecretNumber == true) {
System.out.println("The secret number was " + secretNumber);
break;
}
}
}
System.out.println("Would you like to play again? If so please enter true, if not please enter false.");
playAgain = input.nextBoolean();
if (playAgain == false) {
System.out.println("Thank you for playing, have a good day and wash your hands!");
}
}
}
Methods and functions are your friend. I highly recomend you start learning about them. They will reduce the amount of code you write and make it easier to read. A quick duckduckgo.com search of "java methods" will take you to Tutorialspoint and W3Schools pages.
I recommend using (or learning) the debugger on your IDE (e.g. Netbeans, Eclipse). You will find it makes fault finding hundreds of times easier.
First rule of dealing with user input: don't allow user input.
Other general rules for dealing with user input: Users dont read instructions, users will do the opposite of your instructions, users will try and do things to your program you've never thought of, limit as much as possible all user input, validate every user input everytime.
These are the possible solutions to your errors for you.
Error 1. User input validation will solve this - there is not a requirement for negetive numbers.
Error 2. Putting the game code into a game while loop while(continueGame) will solve this. You start off with boolean continueGame = true. At the end of the game you ask the question "do you want to play again?" yes = true, no = false. The loop will or will not run again dependant on the answer.
Error 3. Change if (numberOfGuesses >= ++secretNumber) to if(numberOfGuessess > secretNumber)
I have been assigned to make a dice game of high or low for my intro to java course. I have all the methods completed, however, I need to use a while loop so that I can continue to play the game until my cash hits 0 or if I bet 0 dollars. I do not want to use a break if I do not have to. So my question is what can I do (if possible) to just only use the while loop? Here is my program:
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int cash = 100;
int bet = 1
while(cash > 0 || bet != 0)
{
bet = getBet(in, cash);
char choice = getHighLow(in);
int roll1 = getRoll();
System.out.println("Dice 1 rolls: " + roll1);
int roll2 = getRoll();
System.out.println("Dice 2 rolls: " + roll2);
int total = (roll1 + roll2);
System.out.println("The total roll is: " + total);
int winnings = determineWinnings(choice, bet, total);
cash = cash + winnings;
}
System.out.println("You have " + cash + " dollars left. Goodbye!");
}
// Given a Scanner and a current maximum amount of money, prompt the user for
// an integer representing the number of dollars that they want to bet. This
// number must be between 0 and to maximum number of dollars. If the user enters
// a number that is out of bounds, display an error message and ask again.
// Return the bet to the calling program.
private static int getBet(Scanner inScanner, int currentPool) {
System.out.println("You have " + currentPool + " dollars");
System.out.println("Enter and amount to bet (0 to quit): ");
int bet = inScanner.nextInt();
while (0 > bet || currentPool < bet )
{
System.out.println("Your bet must be between 0 and " + currentPool + " dollars ");
bet = inScanner.nextInt();
}
return bet;
}
// Given a Scanner, prompt the user for a single character indicating whether they
// would like to bet High ('H'), Low ('L') or Sevens ('S'). Your code should accept
// either capital or lowercase answers, but should display an error if the user attempts
// to enter anything but one of these 3 values and prompt for a valid answer.
// Return the character to the calling program.
private static char getHighLow(Scanner inScanner) {
System.out.println("High, low or sevens (H/L/S): ");
inScanner.nextLine();
char choice = inScanner.nextLine().charAt(0);
choice = Character.toUpperCase(choice);
while (choice != 'H' && choice != 'L' && choice != 'S')
{
System.out.println("You must choose between high, low or sevens (H/L/S): ");
choice = Character.toUpperCase(inScanner.nextLine().charAt(0));
}
return choice;
}
// Produce a random roll of a single six-sided die and return that value to the calling
// program
private static int getRoll() {
Random generate = new Random();
int roll = generate.nextInt(6) + 1;
return roll;
}
// Given the choice of high, low or sevens, the player's bet and the total result of
// the roll of the dice, determine how much the player has won. If the player loses
// the bet then winnings should be negative. If the player wins, the winnings should
// be equal to the bet if the choice is High or Low and 4 times the bet if the choice
// was Sevens. Return the winnings to the calling program.
private static int determineWinnings(char highLow, int bet, int roll) {
if(roll <= 6)
{
if(highLow == 'L')
{
System.out.println("You won " + bet + " dollars! ");
return bet;
}
else
System.out.println("You lose! ");
return -bet;
}
else if (roll == 7)
{
if(highLow == 'S')
{
System.out.println("You won " + (bet * 4) + " dollars! ");
return (bet * 4);
}
else
System.out.println("You lose! ");
return -bet;
}
else
{
if(highLow == 'H')
{
System.out.println("You won " + bet + " dollars! ");
return bet;
}
else
System.out.println("You lose! ");
return -bet;
}
}
}
Change the while(cash > 0 || bet != 0) to while(cash > 0 && bet != 0)
This is because, you want to end the game if either cash equals 0 or when bet equals 0. If you use the || then only when both variables are 0 will the loop stop. If you use the && then the loop will stop if either of the variables are 0.
when && is used, both conditions must be true for the loop to execute. If one condition is true and the other is false then, the loop will stop.
when || is used, any one
condition must be true for the loop to execute. If both conditions are true the the loop will run. If one of the conditions is false and the other is true then, it will still run. If both conditions are false then, the loop will stop.
EDIT:
If you want the program to end as soon as the bet variable is 0 then just add these lines after bet = getBet(in, cash);:
if(bet<=0){
System.out.println("You are out of cash!");
break;
}
Hope this helped:)
//Setting my variables.
Scanner keyboard = new Scanner(System.in); // Initalizing keyboard to scanner input
int quarter;
double balance, intrestRate;
boolean correct = false;
//Loop iterations to resolve error, and determine value for each input.
do{ //Beginning loop for number of quarters, must be between 1-10
System.out.println("Enter a number between 1 and 10 for the amount of quarters");
quarter = keyboard.nextInt();
if(quarter >= 1 && quarter <= 10) //If quarter is between 1 and 10
{
System.out.println("You have " + quarter + " quarters.");
correct = true;
}
else
{
System.out.println("Number of quarters must be between 1 and 10");
correct = false;
}
}while(!correct);
do{ //Second loop for rate of intrest.
System.out.println("Enter intrest rate without percent a sign. Must be greaters than 5% and less than 25%.");
intrestRate = keyboard.nextDouble();
if (intrestRate >= 5 && intrestRate <=25)
{
System.out.println("You have selected a " + intrestRate + "% rate of intrest.");
correct = true;
}
else
{
correct = false;
}
}while(!correct);
}
}
So, this is my code. I'm experimenting with loops, and if-else type statements. I feel like, MY approach is way to complicated and could be easily summarized or revised period. Does anyone know how to approach with, with only declaring one do statement? This code is just in the beginning phases of my experiment and has much work to do. But before I move on, I was hoping for another set of eyes!
Use of infinite loop with break on valid input. Enhanced to handle bad input.
Scanner keyboard = new Scanner(System.in);
int quarter;
while (true) {
System.out.print("Enter number of quarters (1-10): ");
if (keyboard.hasNextInt() && (quarter = keyboard.nextInt()) >= 1 && quarter <= 10)
break;
keyboard.nextLine(); // Discard bad input
System.out.println("Number of quarters must be between 1 and 10");
}
keyboard.nextLine(); // Discard rest of line
System.out.println("You have " + quarter + " quarters.");
double intrestRate;
while (true) {
System.out.print("Enter interest rate (5%-25%), without percent sign: ");
if (keyboard.hasNextDouble() && (intrestRate = keyboard.nextDouble()) >= 5 && intrestRate <= 25)
break;
keyboard.nextLine(); // Discard bad input
System.out.println("Interest rate must be between 5% and 25%");
}
keyboard.nextLine(); // Discard rest of line
System.out.println("You have selected a " + intrestRate + "% rate of interest.");
Hello I am a beginner Java programmer. My Program keeps ending when I put the correct number in (with out printing the message ), or it wont go from a lower number to a higher one with out ending?
Can someone tell me what I am doing wrong?
package week3;
import java.util.Scanner;
public class Week3 {
public static void main(String[] args) {
Scanner In = new Scanner(System.in);
int Guess ;
int count = 0;
count++;
int c = 55;
System.out.println("Welcome to the Higher / Lower game! Try to guess the"
+ "number between 1 and 100. ");
System.out.print("Enter your guess: ");
Guess = In.nextInt();
if(Guess == c)
{
System.out.println("The number was 55 you guessed correctly! "
+ " it took you " + count +" tries");
}//end if
while (Guess < 1)
{
System.out.println("Sorry, the guess needs to be a number between 1 and"
+ " 100. Please try again:");
Guess = In.nextInt();
}//End while < 1
while (Guess > 100)
{
System.out.println("Sorry, the guess needs to be a number between 1 and"
+ " 100. Please try again:");
Guess = In.nextInt();
}//end while <100
while (Guess >= 56)
{
System.out.println("The number is lower.");
Guess = In.nextInt();
} //end while over 55
while (Guess <= 54)
{
System.out.println("The number is higher.");
Guess = In.nextInt();
}//end while lower than 55
}//end main
}//end class
I can see the problem, but you would be better off trying to find it yourself. (Or having another go ...)
Hints:
Try hand-executing the code. Pretend you are the computer, and use a pencil and paper to simulate what it would do.
Have you tried using a debugger?
Some of the comments are good hints too.
While I have your ear, you also should pay attention to your programming style. And one universal style rule for Java is that variables should start with a lower-case letter. Your In and Guess variables violate this.
System.out.println("Welcome to the Higher / Lower game! Try to guess the"
+ "number between 1 and 100. ");
while (true) {
System.out.print("Enter your guess: ");
Guess = Integer.parseint(In.nextLine());
if(Guess == c)
{
System.out.println("The number was 55 you guessed correctly! "
+ " it took you " + count +" tries");
break;
}
if (Guess < 1)
{
System.out.println("Sorry, the guess needs to be a number between 1 and"
+ " 100. Please try again:");
}
if (Guess > 100)
{
System.out.println("Sorry, the guess needs to be a number between 1 and"
+ " 100. Please try again:");
}
if (Guess >= 56)
{
System.out.println("The number is lower.");
}
if (Guess <= 54)
{
System.out.println("The number is higher.");
}
}
}
}
Hopefully this gives you the idea of using the while loop.
The structure of your program is incorrect.
You only need one while loop. Begin your program with a while loop, and continue with conditions, such that:
boolean numFound = false;
while (!numFound) {
//conditions
}