I am trying to prompt the user if the information they entered is correct and the program just proceeds anyway instead of re-prompting the user. I think i need to change how I loop this do some type of do-while loop, but I don't quite know what to do.
{
//Here we will set up our method of data entry and decimal format
Scanner keyboard = new Scanner(System.in);
DecimalFormat eNotation1 = new DecimalFormat("00.00");
//Let's introduce our program to the user
System.out.println("Hi, This is a program to calculate quarterly interest growth");
//Here we will prompt the user to enter the amount of quarters
System.out.println("How many quarters would you like to display? Please pick a number greater than zero and less than or equal to 10");
int quarterNumber = keyboard.nextInt();
if (quarterNumber > 10 || quarterNumber < 0)
{
System.out.println("You entered a number outside of the boundrys. Please run the program again and choose a number between 0 and 10 (number can include 10)");
System.exit(0);
}
//Here we will prompt the user for the starting balance.
System.out.println("What is the starting balance of this account?");
double startingBalance = keyboard.nextDouble();
//Here we will prompt the user for the interest rate
System.out.println("What is the interest rate (in percent) in your area? Please pick a number from 1 - 20.");
double interestRate = keyboard.nextDouble();
if (interestRate < 1 || interestRate > 20)
{
System.out.println("You entered a number outside of the boundrys. Please run the program again and choose a number between 1 and 20 (can include 1 and 20)");
System.exit(0);
}
//Here we will double check with the user that the info is correct.
System.out.println("The amount of quarters you would like displayed is " + quarterNumber);
System.out.println("The starting balance you would like to work with is " + startingBalance);
System.out.println("The interest rate in your area is " + interestRate);
System.out.println("Is this information correct?");
keyboard.nextLine();
String answer = keyboard.nextLine();
System.out.println("");
//We will have them enter the information again if the answer is no or No
if (answer == "no" || answer == "No")
{
//Here we will prompt the user to enter the amount of quarters
System.out.println("How many quarters would you like to display? Please pick a number greater than zero and less than or equal to 10");
keyboard.nextInt();
quarterNumber = keyboard.nextInt();
//Here we will prompt the user for the starting balance.
System.out.println("What is the starting balance of this account?");
keyboard.nextDouble();
startingBalance = keyboard.nextDouble();
//Here we will prompt the user for the interest rate
System.out.println("What is the interest rate (in percent) in your area? Please pick a number from 1 - 20.");
keyboard.nextDouble();
interestRate = keyboard.nextDouble();
}
//Next we will proceed with the calculation if the information is indeed correct
double endingBalance = startingBalance + (startingBalance * (interestRate / 100 * .25));
double interestEarned = endingBalance - startingBalance;
//Now we will output the information
for (int qn = 1; qn < (quarterNumber + 1); qn++ , startingBalance = startingBalance + interestEarned , endingBalance =startingBalance + (startingBalance * (interestRate / 100 * .25)), interestEarned = endingBalance - startingBalance )
{
System.out.println("Quarter Number Starting Balance Interest Earned Ending Balance ");
System.out.println(qn + " " + eNotation1.format(startingBalance) + " " + eNotation1.format(interestEarned) + " " + eNotation1.format(endingBalance) + " ");
}
}
}
I probably figured what your problem is.
Example code snippet: (Note I am doing without an actual java editor so just handle any missing syntax
//Here we will prompt the user to enter the amount of quarters
int quarters = 0;
System.out.println("How many quarters would you like to display? Please pick a number greater than zero and less than or equal to 10");
do
{
quarters = keyboard.nextInt();
if (quarters <= 0 || quarters >= 10)
{
System.out.println("You entered a number outside of the boundrys. Please Type a number greater than 0 and less than equal to 10 again)");
}
}
while (quarters <= 0 || quarters >= 10)
The idea is for a recursive prompt. The application first prompts the user to type in the result, and then you handle the amount of So you have to handle the prompt within the do-while loop. Assuming you don't want to repeat the same old text, you can do what I did (which is much cleaner in my opinion).
EDIT: Assuming you want to handle the entire repeating of the application. place everything for the declaration of variables into a method (or better various methods for cleaner handling, and handle something like this.
int quarters;
double balance;
//TODO : Add all other required variables
string verification;
do
{
quarters = getNumberOfQuartersFromUser();
balance = getStartingBalance();
... //TODO : all the other methods
//verification
System.out.println("Is this accepted?");
verification = keyboard.nextString();
//Handle verfication if it is no or No
if (verification == null || verification == "No" || verification == "no")
{
System.out.println("Starting from the beginning again");
}
}
while (verification == null || verification == "No" || verification == "no")
//out of loop, so handle calculation.
...
and a method snippet
private int getNumberOfQuartersFromUser()
{
int quarters = 0;
System.out.println("How many quarters would you like to display? Please pick a number greater than zero and less than or equal to 10");
do
{
quarters = keyboard.nextInt();
if (quarters <= 0 || quarters >= 10)
{
System.out.println("You entered a number outside of the boundrys. Please Type a number greater than 0 and less than equal to 10 again)");
}
}
while (quarters <= 0 || quarters >= 10)
return quarters;
}
I think you should enclose your codes to Else statement to avoid proceeding unintentionally. Remember that else limits the run-time of your codes and put it on a more specified path for you.
{
//Here we will set up our method of data entry and decimal format
Scanner keyboard = new Scanner(System.in);
DecimalFormat eNotation1 = new DecimalFormat("00.00");
//Let's introduce our program to the user
System.out.println("Hi, This is a program to calculate quarterly interest growth");
//Here we will prompt the user to enter the amount of quarters
System.out.println("How many quarters would you like to display? Please pick a number greater than zero and less than or equal to 10");
int quarterNumber = keyboard.nextInt();
//Here you had started your condition I'll try to make it nested if statement
if (quarterNumber > 10 || quarterNumber < 0)
//if the condition is true perform this
{
System.out.println("You entered a number outside of the boundrys. Please run the program again and choose a number between 0 and 10 (number can include 10)");
System.exit(0);
}
else{
//if false conditions inside else statement should be performed
//Here we will prompt the user for the starting balance.
System.out.println("What is the starting balance of this account?");
double startingBalance = keyboard.nextDouble();
//Here we will prompt the user for the interest rate
System.out.println("What is the interest rate (in percent) in your area? Please pick a number from 1 - 20.");
double interestRate = keyboard.nextDouble();
//you could put another if statement inside if statement which is known as nested if statement.
if (interestRate < 1 || interestRate > 20)
{
System.out.println("You entered a number outside of the boundrys. Please run the program again and choose a number between 1 and 20 (can include 1 and 20)");
System.exit(0);
}
else{
//like before you should enclose this to else to avoid confusion
//Here we will double check with the user that the info is correct.
System.out.println("The amount of quarters you would like displayed is " + quarterNumber);
System.out.println("The starting balance you would like to work with is " + startingBalance);
System.out.println("The interest rate in your area is " + interestRate);
System.out.println("Is this information correct?");
keyboard.nextLine();
String answer = keyboard.nextLine();
System.out.println("");
//We will have them enter the information again if the answer is no or No
if (answer == "no" || answer == "No")
{
//Here we will prompt the user to enter the amount of quarters
System.out.println("How many quarters would you like to display? Please pick a number greater than zero and less than or equal to 10");
keyboard.nextInt();
quarterNumber = keyboard.nextInt();
//Here we will prompt the user for the starting balance.
System.out.println("What is the starting balance of this account?");
keyboard.nextDouble();
startingBalance = keyboard.nextDouble();
//Here we will prompt the user for the interest rate
System.out.println("What is the interest rate (in percent) in your area? Please pick a number from 1 - 20.");
keyboard.nextDouble();
interestRate = keyboard.nextDouble();
}
//Next we will proceed with the calculation if the information is indeed correct
double endingBalance = startingBalance + (startingBalance * (interestRate / 100 * .25));
double interestEarned = endingBalance - startingBalance;
//Now we will output the information
for (int qn = 1; qn < (quarterNumber + 1); qn++ , startingBalance = startingBalance + interestEarned , endingBalance =startingBalance + (startingBalance * (interestRate / 100 * .25)), interestEarned = endingBalance - startingBalance )
{
System.out.println("Quarter Number Starting Balance Interest Earned Ending Balance ");
System.out.println(qn + " " + eNotation1.format(startingBalance) + " " + eNotation1.format(interestEarned) + " " + eNotation1.format(endingBalance) + " ");
}
}
}
}
Remember that learning nested if statement is essential to a programmer. without this, all your conditions will literally proceed.
Related
if the user enters an invalid weight or age the program is supposed to display an error message immediately and end the program. my program displays an error message after both the age and weight are entered. can anyone help me? example: user enters 1 for the switch statement to choose to enter the age in months and weight in kg. if the user enters -5 for the months it should display error message right away and end the program. instead what my program does is after the -5 has been entered for the age it will prompt the user to then enter the weight. after the weight is entered it then gives me the error message and ends my program. any help will be much appreciated.
import java.util.Scanner;
import java.lang.Math;
public class infant{
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int number;
double ageMonths = 0;
double ageYears = 0;
double weightPounds = 0;
double weightKg = 0;
System.out.println( "Choice 1 input the age in months, then weight in kilograms"); // this tells the user what the numbers 1-4 does when chosen
System.out.println( "Choice 2 input the age in years, weight in kilograms");
System.out.println( "Choice 3 input the age in months, weight in pounds");
System.out.println( "Choice 4 input the age in years, weight in pounds");
number =sc.nextInt();
if(number<=4 && number>=1){ // if statement that makes the user enter a value from 1 to 4 for the switch statment.
System.out.println("valid number selection");
}else{ System.out.println("need to choose a number between 1 and 4");
return;
}
switch(number){ // switch statment that allows the user to choose how they want to enter the height and weight
case 1: System.out.println("age in months: "); ageMonths =sc.nextDouble();
System.out.println("weight in kilograms: "); weightKg =sc.nextDouble();
ageYears = ageMonths * 0.0833334; // this switch statment also converts Kg to pounds and years to months in order for math equation in the if statement at then end of the program to work.
weightPounds = weightKg * 2.20462;
break;
case 2: System.out.println("age in years: "); ageYears =sc.nextDouble();
System.out.println("weight in kilograms: "); weightKg =sc.nextDouble();
ageMonths = ageYears * 12;
weightPounds = weightKg * 2.20462;
break;
case 3: System.out.println("age in months: "); ageMonths =sc.nextDouble();
System.out.println("weight in pounds: "); weightPounds =sc.nextDouble();
ageYears = ageMonths * 0.0833334;
weightKg = weightPounds * 0.453592;
break;
case 4: System.out.println("age in years: "); ageYears =sc.nextDouble();
System.out.println("weight in pounds: "); weightPounds =sc.nextDouble();
ageMonths = ageYears * 12;
weightKg = weightPounds * 0.453592;
break;
default: System.out.println("you entered in an invalid number");
}
if(ageMonths<=24 && ageMonths>-0.1){ // if statement that makes sure the ages are in the correct range
System.out.println("valid age input");
}else if(ageYears>-0.1 && ageYears<=2){
System.out.println("valid age input");
}else{ System.out.println("You entered a invaild age 0 to 24 months only");
return;
}
if(weightPounds>=4.40925 && weightPounds<=33.0693 || weightKg>=2 && weightKg<=15){ // if statement that makes sure the weight are in the correct range
System.out.println("valid weight input");
}else{ System.out.println("You entered a invaild weight 2kg to 15kg only");
return;
}
if(weightKg >= ageYears * ageMonths / 3 + 2 && weightKg <= 5 * ageYears * ageMonths / 12 + 5){ // if statement that does a math equation to determine if your infant is healthy or not
System.out.println(" your infant is healthy");
}else{ System.out.println(" your infant is not healthy");
}
}
}
If you really want to just end your program with invalid input, you could always use System.exit(0) instead of "return." That's guaranteed to end the program.
for instance:
if(number<=4 && number>=1){ // if statement that makes the user enter a value from 1 to 4 for the switch statment.
System.out.println("valid number selection");
}else{ System.out.println("need to choose a number between 1 and 4");
System.exit(0);
}
Unless I'm mistaken, that should terminate the main thread immediately after the print statement.
The code for checking the weights and months, you keep the code for both in some different functions and then inside the switch case after you have entered the months, then call the function with that month entered and then you can do the same thing for the weights, this way you can have a structure you want.. Do ask if you need any kind of clarification.
function checkMonths(double ageMonths){
if(ageMonths<=24 && ageMonths>-0.1){ // if statement that makes sure the ages are in the correct range
System.out.println("valid age input");
}else{ System.out.println("You entered a invaild age 0 to 24 months only");
return;
}
}
function checkYears(double ageYears){
if(ageYears>-0.1 && ageYears<=2){
System.out.println("valid age input");
}else{ System.out.println("You entered a invaild age 0 to 24 months only");
return;
}
}
function checkWeights(double weightPounds){
if(weightPounds>=4.40925 && weightPounds<=33.0693 || weightKg>=2 && weightKg<=15){ // if statement that makes sure the weight are in the correct range
System.out.println("valid weight input");
}else{ System.out.println("You entered a invaild weight 2kg to 15kg only");
return;
}
}
Do change the variable names inside the function argument according to your usage.
Need to be able to loop if user selects one of the two options it should terminate, if user selects invalid option keep looping until one of the options is selected
import java.util.Scanner;
public class conversion {
public static void main(String[] args){
Scanner input = new Scanner(System.in);
System.out.println("Which conversion do you want?");
System.out.println("Pounds to Kilograms(enter 1)");
System.out.println("Kilograms to Pounds(enter 2)");
double kilograms, pounds;
int choice = input.nextInt();
while(){
if(choice == 1){
System.out.println("What weight value do you want converted?");
pounds = input.nextDouble();
kilograms = pounds / 2.20462;
kilograms = Math.round(kilograms * 100.0) / 100.0;
System.out.println( +pounds+ " pounds is equal to " +kilograms+ " kilograms");
}
else if(choice == 2){
System.out.println("What weight value do you want converted?");
kilograms = input.nextDouble();
pounds = kilograms/0.453592;
pounds = Math.round(pounds * 100.0) / 100.0;
System.out.println( +kilograms+ " kilograms is equal to " +pounds+ " pounds");
}
else if((choice != 1) || (choice != 2)){
System.out.println("Invalid please try again");
System.out.println("Which conversion do you want?");
System.out.println("Pounds to Kilograms(enter 1)");
System.out.println("Kilograms to Pounds(enter 2)");
choice = input.nextInt();
}
}
}
}
show a menu of choices;
ask the user which operation they want;
read in the user response;
determine if it is an acceptable response, repeat request if not.
compute and display the result
Display the menu and ask the user which conversion they want:
Which conversion do you want?
Then ask the user for what weight value should be converted.
What weight value do you want converted?
If the user chooses 1, then convert the pounds to Kilograms, else if the user chooses 2 convert the kilograms to pounds, else if the user choice is anything else, tell the user their answer is invalid and request another answer.
Use while (true). Put a break; when you want to exit the loop
Put int choice = input.nextInt(); at the top, inside of the loop instead of at the end too.
Can also just use else to capture all possible invalid input.
double kilograms, pounds;
while (true) {
System.out.println("Which conversion do you want?");
System.out.println("Pounds to Kilograms(enter 1)");
System.out.println("Kilograms to Pounds(enter 2)");
int choice = input.nextInt();
if (choice == 1) {
// okay
lbsToKg(); // TODO: implement
break; // stops the loop
} else {
// invalid, will already continue the loop
}
I have been struggling with this for the last two days. I have no idea at what point in my code I am making the mistake. Please help!
import java.util.Scanner;
class Program3
{
private static Scanner inp;
public static void main(String args[])
{
double number1;
double number2;
inp = new Scanner(System.in);
double repeat = 0;
do
{
System.out.println("Please enter a number.");
number1 = inp.nextDouble();
System.out.println("Please enter a second number.");
number2 = inp.nextDouble();
System.out.println(" You have chosen numbers, " +number1+ ", and " +number2++);
double add;
double subtract;
double multiply;
double divide;
double choice;
add = number1+number2;
subtract = number1-number2;
multiply = number1*number2;
divide = number1/number2;
System.out.println("What type of operation would you like to run? ");
System.out.println("Please enter the number that corresponds with the operation.");
System.out.println("Please note, that if your dividing number is equal to 0, the operation will return and error message.");
System.out.println("1. add");
System.out.println("2. subtract");
System.out.println("3. multiply");
System.out.println("4. divide");
choice = inp.nextInt();
if (choice == 1)
{choice = add;
System.out.println("By adding " +number1+ " to " +number2+ " the answer is " +choice++);
}
else if (choice == 2)
{choice = subtract;
System.out.println("By subtracting " +number1+ " and " +number2+ " the answer is " +choice++);
}
else if (choice == 3)
{choice = multiply;
System.out.println("By multiplying " +number1+ " by " +number2+ " the answer is " +choice++);
}
else if (choice == 4)
{choice = divide;
System.out.println("By dividing " +number1+ " from " +number2+ " the answer is " +choice++);
}
if (number2 == 0)
System.out.println("Error: Number cannot be divisible by 0. Please choose another number");
System.out.println("Would you like to try other numbers?");
System.out.println("Enter 1 to continue");
repeat = inp.nextDouble();
} while (repeat == 1);
inp.close();
}
}
Here is the result
Please enter a number.
2
Please enter a second number.
3
You have chosen numbers, 2.0, and 3.0
What type of operation would you like to run?
Please enter the number that corresponds with the operation.
Please note, that if your dividing number is equal to 0, the operation will return and error message.
1. add
2. subtract
3. multiply
4. divide
1
By adding 2.0 to 4.0 the answer is 6.0
Would you like to try other numbers?
Enter 1 to continue
As you can see. the number input by the user and the number in the operation have a difference of 1 and I cannot find the mistake in the code. Thanks for your help!
In the following line
System.out.println(" You have chosen numbers, " +number1+ ", and " +number2++);
You are incrementing number2 by one, by doing this
number2++
This is known as an increment, and what this does is to increment the value of a numeric variable by adding 1.
Remove those ++ at the end, and it should work.
When you do "choice++", that means to increment the value of "choice" by one.
Here's a short description.
The answer is already posted here.
but instead of using if-else condition on choice, you must use switch statements and make cases according to user choice.
take a look at
Why the switch statement and not if-else?
I am trying to create a while loop where the user has a total of three tries to enter a valid number. I'm not understanding how the system recognizes that 3 invalid attempts have been made before displaying the message.
Classes, variables, and scanner objects are made. After the three attempts, I want to say "No more tries". I already have the program written to use the user's input for quantity if its valid. This is just if they input three invalid attempts.
Updated code:
int quantity = 0;
// Get user's desired amount of lemonade cups
System.out.print("Hello " + name + ". How many cups of lemonade can I get you? ");
quantity = keyboard.nextInt(); // Store amount of cups wanted
int attempts = 0;
int maxAttempts = 3;
double subTotal = quantity * lemonadeCost;
double totalTax = subTotal * 0.08;
double totalPrice = subTotal + totalTax;
while (attempts < maxAttempts) {
if (quantity < 1 || quantity >= 20) {
System.out.println("That is an invalid amount, please try again");
quantity = keyboard.nextInt(); }
else {
System.out.println("Subtotal: " + defaultFormat.format(subTotal));
System.out.println("Tax: " + defaultFormat.format(totalTax));
System.out.println("Total: " + defaultFormat.format(totalPrice));
}
attempts++;
if (attempts >= 3) {
System.out.print ("No lemonade for you");
break;
}
// Ask for user's payment method
Scanner method = new Scanner(System.in);
System.out.println("How would you like to pay? Enter 'm' for money, 'c' for credit or 'g' for gold. ");
String payment = method.nextLine();
dxdy is correct about the braces required for making the while() loop function.
Once the while loop has ended (either quantity is between 1 and 20, or attempts > maxAttempts), you just need to have an if statement like the following:
if (attempts > maxAttempts) {
System.out.println("No more tries);
return -1; // or something else to break out of your code
}
and then continue on with the rest of your code working with the quantity variable.
You seem to be missing the opening and closing brackets for the loop. As it is, your code reads
while (quantity < 1 || quantity >= 20 && attempts <= maxAttempts)
System.out.println("That is an invalid amount, please try again");
// these below are not part of the loop
quantity = keyboard.nextInt();
attempts++;
Instead you should do
while (quantity < 1 || quantity >= 20 && attempts <= maxAttempts){
System.out.println("That is an invalid amount, please try again");
quantity = keyboard.nextInt();
attempts++;
}
try this code:
//start with 1 since the user will attempt it at least one time.
int attempts = 1;
int maxAttempts = 3;
int quantity=0;
Scanner keyboard = new Scanner(System.in);
//LESS THAN OR EQUAL TO 3...
while(attempts<=maxAttempts){
System.out.print("Enter amount: ");
quantity = keyboard.nextInt();
//check if valid
if(quantity < 1 || quantity >= 20){
//check if it's 1st and 2nd trial.
if(attempts<maxAttempts){
System.out.println("That is an invalid amount, please try again");
}else{
//third trial and still invalid
System.out.print("No more tries");
}
}else{
//user entered a valid amount so let's break the loops.
System.out.println("The amount is valid. Value of amount: "+ quantity);
break;
}
//increment attempts
attempts++;
}
//never forget to close the scanner
keyboard.close();
}
}
Though I could have turned this into methods if it's allowed
EDIT: As you updated the question, so it was necessary to update the answer too. Here it is what you actually want.
public static void main(String[] args) {
// Get user's desired amount of lemonade cups
String name = "Jimmy Nguyen";
Scanner keyboard = new Scanner(System.in);
int quantity;// Store amount of cups wanted
int lemonadeCost = 4; // Suppose
int attempts = 0;
int maxAttempts = 3;
System.out.print("Hello " + name + ". How many cups of lemonade can I get you? ");
while (attempts < maxAttempts) {
quantity = keyboard.nextInt();
if (quantity < 1 || quantity >= 20) {
System.out.println("That is an invalid amount, please try again\n");
++attempts;
} else {
double subTotal = quantity * lemonadeCost;
double totalTax = subTotal * 0.08;
double totalPrice = subTotal + totalTax;
System.out.println("Subtotal: " + subTotal);
System.out.println("Tax: " + totalTax);
System.out.println("Total: " + totalPrice);
// Ask for user's payment method
System.out.println("How would you like to pay? Enter 'm' for money, 'c' for credit or 'g' for gold. ");
keyboard.nextLine();
String payment = keyboard.nextLine();
break;
}
if (attempts >= 3) {
System.out.print("No lemonade for you");
break;
}
}
}
I am writing a loan calculate with data validation. My maximum loan amount is 1,000,000 and I am using the method below to validate. When I enter 1,000,000 into the program it comes back with my error method. I thought (d >= max) would allow me to go up to and including my max. Can anyone see a problem with this method or is it possible I should be looking elsewhere in my code for a problem.
Any help is appreciated.
public static double getDoubleWithinRange(Scanner sc, String prompt, double min, double max)
{
double d = 0.0;
boolean isValid = false;
while (isValid == false)
{
d = getDouble (sc, prompt);
if (d <= min)
{
System.out.println(
"Error! Number must be greater than " + min + "." );
}
else if (d >= max)
{
System.out.println("Error! Number must be less than " + max + "." );
}
else
isValid = true;
}
return d;
//Get input from user
System.out.println("DATA ENTRY");
double loanAmount = getDoubleWithinRange (sc,
"Enter loan amount: ",0, 1000000);
double interestRate = getDoubleWithinRange (sc,
"Enter yearly interest rate: " , 0, 20);
int years = getIntWithinRange (sc,
"Enter number of years: ",0,100);
you are saying if the amount is greater than or equal to one million cause an error. you want to say if it is greater than show an error
Use else if (d>max), since you want up to 1,000,000 (and 1,000,000 can be included).