How to implement a for loop inside a while loop? - java

sorry for asking such an in depth question, but I'm very lost. I am working on a problem and I am stuck. I am supposed to make a basic menu driven calculator that add, subtract, multiply, divide, or generate a random number between an upper and lower limit. I made that without too much difficulty, but now I need to change it so that after it performs an operation it starts over again and displays the menu. Also, if I enter an invalid response, it needs to let them try again until they enter a valid one UNLESS they enter an invalid response THREE TIMES IN A ROW; then it needs to display a message about trying again later and exiting the program. This is there I am stuck. I have tried every combination of for and while in the following code but i can not get this to work. I would really appreciate any pointers.
Here are the requirements:
The menu is repeatedly displayed until a valid option is entered
If the user enters three invalid choices in a row, the program ends
If the user enters two invalid choices, then a valid one, then another invalid one, the program does NOT end
The program computes the correct answers for each menu option
The program continues after a valid operation by re-displaying the menu
The program ends when the user chooses the Quit option from the menu
• The program does not end on division by zero – just display an error message and allow the user to retry
And here is what i have thus far.
import java.util.Scanner;
public class BasicCalculator {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
double numONE = 0.0;
double numTWO = 0.0;
double upperLimit = 0.0;
double lowerLimit = 0.0;
System.out.println("MENU");
System.out.println("1. +");
System.out.println("2. -");
System.out.println("3. *");
System.out.println("4. /");
System.out.println("5. Generate a random number.");
System.out.println("6. Quit");
System.out.println("What would you like to do?");
int menuSelect = input.nextInt();
//Selects an item from the menu
if(menuSelect == 1 || menuSelect == 2 || menuSelect == 3 || menuSelect == 4){
System.out.println("Enter first number.");
numONE = input.nextDouble();
//Stores input as numONE
System.out.println("Enter second number.");
numTWO = input.nextDouble();
//Stores input as numTWO
}
if(menuSelect == 1){
System.out.println(numONE + numTWO);
//Adds two numbers
}
else if(menuSelect == 2){
System.out.println(numONE - numTWO);
//Subtracts second number from first number
}
else if(menuSelect == 3){
System.out.println(numONE * numTWO);
//Multiplies two numbers
}
else if(menuSelect == 4){
if(numTWO != 0){
System.out.println(numONE / numTWO);
//Divides first number by second number
}
else if(numTWO == 0){
System.out.println("I'm sorry, you cannot divide by zero.");
}
}
else if(menuSelect == 5){
System.out.println("Enter upper limit.");
upperLimit = input.nextDouble();
System.out.println("Enter lower limit.");
lowerLimit = input.nextDouble();
double randomVal = (lowerLimit + (int)(Math.random() * ((upperLimit - lowerLimit)+1)));
System.out.println(randomVal);
//Displays a random integer between an upper and a lower limit
}
else if(menuSelect==6){
System.out.println("Goodbye");
System.exit(0);
}
else{
System.out.println("Sorry, "+menuSelect+" is not an option.");
}
}
}

Look at lines I added ( // <- new code )
import java.util.Scanner;
public class BasicCalculator {
public static void main(String[] args) {
int counter_WrongAttempts = 0; // <- new code
boolean flag_Quit = false; // <- new code
while (!flag_Quit) { // <- new code
boolean wrongAttempt = false; // <- new code
Scanner input = new Scanner(System.in);
double numONE = 0.0;
double numTWO = 0.0;
double upperLimit = 0.0;
double lowerLimit = 0.0;
System.out.println("MENU");
System.out.println("1. +");
System.out.println("2. -");
System.out.println("3. *");
System.out.println("4. /");
System.out.println("5. Generate a random number.");
System.out.println("6. Quit");
System.out.println("What would you like to do?");
int menuSelect = input.nextInt();
//Selects an item from the menu
if(menuSelect == 1 || menuSelect == 2 || menuSelect == 3 || menuSelect == 4){
System.out.println("Enter first number.");
numONE = input.nextDouble();
//Stores input as numONE
System.out.println("Enter second number.");
numTWO = input.nextDouble();
//Stores input as numTWO
}
if(menuSelect == 1){
System.out.println(numONE + numTWO);
//Adds two numbers
}
else if(menuSelect == 2){
System.out.println(numONE - numTWO);
//Subtracts second number from first number
}
else if(menuSelect == 3){
System.out.println(numONE * numTWO);
//Multiplies two numbers
}
else if(menuSelect == 4){
if(numTWO != 0){
System.out.println(numONE / numTWO);
//Divides first number by second number
}
else if(numTWO == 0){
System.out.println("I'm sorry, you cannot divide by zero.");
}
}
else if(menuSelect == 5){
System.out.println("Enter upper limit.");
upperLimit = input.nextDouble();
System.out.println("Enter lower limit.");
lowerLimit = input.nextDouble();
double randomVal = (lowerLimit + (int)(Math.random() * ((upperLimit - lowerLimit)+1)));
System.out.println(randomVal);
//Displays a random integer between an upper and a lower limit
}
else if(menuSelect==6){
System.out.println("Goodbye");
System.exit(0);
flag_Quit = true; // <- new code
}
else{
System.out.println("Sorry, "+menuSelect+" is not an option.");
wrongAttempt = true; // <- new code
}
if (wrongAttempt) // <- new code
counter_WrongAttempts++; // <- new code
else // <- new code
counter_WrongAttempts = 0; // <- new code
flag_Quit = flag_Quit || (counter_WrongAttempts >= 3); // <- new code
}
}
}

This isn't about a 'for loop inside a while loop', you don't even need it.
Imagine the following pseudo-code:
int invalidOptions = 0;
while ( invalidOptions < 3 ) {
// show menu
displayMenu();
// read option
int input = readInput();
// validate input
if ( isInputValid(input) ) {
// check whether the user wants to exit or not
if (input == EXIT_INPUT) {
break;
}
// handle other commands
handleInput(input);
} else {
// input is invalid
invalidOptions++;
}
}
That's all you need, it's better to split your program into smaller pieces, it will be easier to maintain and understand.

First things first, you don't really need four variables for this program. Since you are always taking two numbers as input you can easily store them in two variables, instead of having different variable names for each case.
As mentioned above, you don't need such complex loop nesting. A simple while that checks the number of errors is less than 3 will do just fine. Also, you seem to work well with the System.out.println() command, but for some applications, like input, it may be better to work with System.out.print(), it's basically the same but does not start a new line. Try the code below to see the results.
Another thing you might consider is using a switch sentence instead of the if, else if, else if statements.
import java.util.Scanner;
public class BasicCalculator {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
double firstNumber = 0.0;
double secondNumber = 0.0;
//New variable
int errors = 0;
while (errors < 3) {
System.out.println("MENU");
System.out.println("1. +");
System.out.println("2. -");
System.out.println("3. *");
System.out.println("4. /");
System.out.println("5. Generate a random number.");
System.out.println("6. Quit");
System.out.println("What would you like to do?");
System.out.print("> ");
int menuSelect = input.nextInt();
//Selects an item from the menu
if(menuSelect == 1 || menuSelect == 2 || menuSelect == 3 || menuSelect == 4) {
errors = 0;
System.out.print("Enter first number: ");
firstNumber = input.nextDouble();
//Stores input as the firstNumber
System.out.print("Enter second number: ");
secondNumber = input.nextDouble();
//Stores input as the secondNumber
}
if(menuSelect == 1){
System.out.println(firstNumber + secondNumber);
//Adds two numbers
}
else if(menuSelect == 2){
System.out.println(firstNumber - secondNumber);
//Subtracts second number from first number
}
else if(menuSelect == 3){
System.out.println(firstNumber * secondNumber);
//Multiplies two numbers
}
else if(menuSelect == 4){
if(secondNumber != 0){
System.out.println(firstNumber / secondNumber);
//Divides first number by second number
}
else if(secondNumber == 0){
System.out.println("I'm sorry, you cannot divide by zero.");
}
}
else if(menuSelect == 5){
errors = 0;
System.out.print("Enter upper limit: ");
firstNumber = input.nextDouble();
System.out.print("Enter lower limit: ");
secondNumber = input.nextDouble();
double randomVal = (firstNumber + (int)(Math.random() * ((firstNumber - secondNumber)+1)));
System.out.println(randomVal);
//Displays a random integer between an upper and a lower limit
}
else if (menuSelect==6){
System.out.println("Goodbye");
System.exit(0);
}
else{
errors++;
System.out.println("Sorry, "+ menuSelect + " is not an option.");
}
}
input.close();
System.out.println("Program will exit now");
}
}

int unvalid = 0;
while (unvalid < 3)
{
//read stuff
if ([stuff is valid])
{
unvalid = 0;
}
else
{
unvalid++;
}
}

You probably don't want a for loop inside a while loop to handle this. I would just have a variable to track how many invalid inputs you've received, increment it when they enter something invalid, reset it to zero if they enter something valid, and kick them out if it gets too high.
eg:
import java.util.Scanner;
public class BasicCalculator {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
double numONE = 0.0;
double numTWO = 0.0;
double upperLimit = 0.0;
double lowerLimit = 0.0;
int invalid = 0;
System.out.println("MENU");
System.out.println("1. +");
System.out.println("2. -");
System.out.println("3. *");
System.out.println("4. /");
System.out.println("5. Generate a random number.");
System.out.println("6. Quit");
System.out.println("What would you like to do?");
int menuSelect = input.nextInt();
//Selects an item from the menu
while(invalid < 3){
if(menuSelect == 1 || menuSelect == 2 || menuSelect == 3 || menuSelect == 4){
System.out.println("Enter first number.");
numONE = input.nextDouble();
//Stores input as numONE
System.out.println("Enter second number.");
numTWO = input.nextDouble();
//Stores input as numTWO
invalid = 0;
}
if(menuSelect == 1){
System.out.println(numONE + numTWO);
//Adds two numbers
}
else if(menuSelect == 2){
System.out.println(numONE - numTWO);
//Subtracts second number from first number
}
else if(menuSelect == 3){
System.out.println(numONE * numTWO);
//Multiplies two numbers
}
else if(menuSelect == 4){
if(numTWO != 0){
System.out.println(numONE / numTWO);
//Divides first number by second number
}
else if(numTWO == 0){
System.out.println("I'm sorry, you cannot divide by zero.");
}
}
else if(menuSelect == 5){
System.out.println("Enter upper limit.");
upperLimit = input.nextDouble();
System.out.println("Enter lower limit.");
lowerLimit = input.nextDouble();
double randomVal = (lowerLimit + (int)(Math.random() * ((upperLimit - lowerLimit)+1)));
System.out.println(randomVal);
//Displays a random integer between an upper and a lower limit
invalid = 0;
}
else if(menuSelect==6){
System.out.println("Goodbye");
System.exit(0);
}
else{
System.out.println("Sorry, "+menuSelect+" is not an option.");
invalid++;
}
}
System.out.println("Too many invalid inputs. Try again later");
}
}

Related

Illegal start of expression on my function public static void

My code is about looping and method, A program that will let user either compute an area or use the 4 basic math operations. the (Triangle, Square,Rectangle) with their choice of process: Addition, Subtraction, Multiplication and Division.
I think i properly closed the addition function there and i already check the closing every functions they seem work well other than the addtion function since thats the only error i got.
import java.util.Scanner;
public class Main{
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
//WHILE LOOP FOR CHOICES
while(true){//CHOICES LOOP
System.out.println("∘₊✧─────────────────────────────────────✧₊∘");
System.out.println("Input Choice of Process");
System.out.println("1 - Addition process");
System.out.println("2 - Subtraction process");
System.out.println("3 - Multiplication process");
System.out.println("4 - Division process");
System.out.println("5 - Compute process");
System.out.println("Your choice: ");
int option = scan.nextInt();
System.out.println("∘₊✧─────────────────────────────────────✧₊∘");
if(option == 1){
Add();
}
else if(option == 2){
Sub();
}
else if(option == 3){
Mul();
}
else if(option == 4){
Div();
}
else if(option == 5){
Com();
}
else if((option>=6)&&(option<=100)){//INVALID
System.out.println("Invalid Input, Please Input Choice Again.");
}
else{//- if user input other number, the program will break and stop from looping
break;
}
Here Im getting a error here im not sure what is it
public static void Add(){
System.out.println("ADDITION");
System.out.println("Enter two numbers: ");
System.out.println("1st number: ");
int add1=scan.nextInt();
System.out.println("2nd number: ");
int add2=scan.nextInt();
int addtotal=add1+add2;
if(addtotal>100){// In addition, if the sum is higher than 100, print the answer the word high. if equal and below 100, print low
System.out.println("Total is "+addtotal+" High");
}
else if(addtotal<100){
System.out.println("Total is "+addtotal+" Low");
}
}
public static void Sub(){//SUBTRACTION
System.out.println("SUBTRACTION");
System.out.println("Enter two numbers: ");
System.out.println("1st number: ");
int sub1=scan.nextInt();
System.out.println("2nd number: ");
int sub2=scan.nextInt();
int subtotal=sub1-sub2;
if(subtotal<0){// In subtraction, if the difference is negative, print invalid. If 0 or above, print the difference and the word valid.
System.out.println("Invalid ");
}
else if(subtotal>0){
System.out.println("Total is "+subtotal+" Valid");
}
}
public static void Mul(){//MULTIPLICATION
System.out.println("MULTIPLICATION");
System.out.println("Enter two numbers: ");
System.out.println("1st number: ");
double multi1=scan.nextDouble();//In multiplication, make it accepts decimal value
System.out.println("2nd number: ");
double multi2=scan.nextDouble();
double multitotal=multi1*multi2;
System.out.println("Total is "+multitotal);
}
public static void Div(){
System.out.println("DIVISION");
System.out.println("Enter two numbers: ");
System.out.println("1st number: ");
int div1=scan.nextInt();
System.out.println("2nd number: ");
int div2=scan.nextInt();
int divtotal= div1 / div2;
int divremainder= div1 % div2;//In division, if it has remainder, print the answer and the remainder.
System.out.println("Total is "+divtotal);
System.out.println("Remainder is "+divremainder);
}
public static void Com(){// If user choose 5, the user needs to choose again on a ,b or c. If other letter, print invalid and then go pack on choosing of process.
System.out.println("∘₊✧─────────────────────────────────────✧₊∘");
System.out.println("Input Choice of Process");
System.out.println("a - Rectangle");
System.out.println("b - Square");
System.out.println("c - Triangle");
System.out.println("Your choice: ");
Scanner Keyboard = new Scanner(System.in);
Scanner input = new Scanner(System.in);
char choice = Keyboard.nextLine().charAt(0);
System.out.println("∘₊✧─────────────────────────────────────✧₊∘");
if (choice == 'A' || choice == 'a')//rectangle
{
System.out.println("Enter length of rectangle's base: ");
double base = input.nextDouble();
System.out.println("Enter length of rectangle's height: ");
double height = input.nextDouble();
double rArea = base * height;
System.out.println("The area of a rectangle with a base length of " + base + " and a height of " + height + " is " + rArea + ".");
}
else if (choice == 'B' || choice == 'b') //square
{
System.out.println("Enter length of square's sides: ");
double sSide = input.nextDouble();
double sArea = sSide * sSide;
System.out.println("The area of a square with a side length of " + sSide + " is " + sArea + ".");
}
else if (choice == 'C' || choice == 'c') //traingle
{
System.out.println("Enter traingle's side length: ");
double tSide = input.nextDouble();
double tArea = tSide * tSide * tSide;
System.out.println("The area of a triangle with a side length of " + tSide + " is " + tArea + ".");
}
else //invalid
{
System.out.println("You've entered an invalid character.");
}
}
}
You haven't got a closing brace for your main method

There is an error in my java coding when I put a grade percentage for my gradebook application

I have an application that acts as a gradebook. However, in the console log when I type in a grade there seems to be an error. I was hoping someone could fix this to where I am able to put in a grade percentage and the error does not pop up.enter code here
Below is what the error says:java.lang.NumberFormatException: For input string: "70%"
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:580)
at java.lang.Integer.parseInt(Integer.java:615)
at Gradebook.getScores(Gradebook.java:45)
at Gradebook.main(Gradebook.java:154)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at edu.rice.cs.drjava.model.compiler.JavacCompiler.runCommand(JavacCompiler.java:272)
Here is my code:
import java.util.Scanner;
public class Gradebook {
//getNumStudents takes a Scanner object as parameter
//the reader object lets us take user input
public static int getNumStudents(Scanner reader){
int numStudents = 0;
//we get the number of students
do{
System.out.print("Enter number of students: ");
numStudents = Integer.parseInt(reader.nextLine());
//we determine if the user input is valid
//it should be greater than 0
//because we don't want the number o students to be negative
//if it is not valid then we keep taking inputs
if(numStudents > 0){
break;
}else{
System.out.println("Please enter atleast 1 student.");
}
}while(true);
System.out.println("================================================================================================================================================");
//we return numStudents
return numStudents;
}
//getScores takes our Scanner object again and the number student as parameter this time
public static String[] getScores(Scanner reader, int numStudents){
//we create an array of string studInfo
//that will be returned containing the name, and scores of our students
String[] studInfo = new String[numStudents];
String name = "";
int quiz = 0;
int assign = 0;
int test1 = 0;
int test2 = 0;
//we use a for loop to keep taking student scores
for(int i = 0; i < numStudents; i++){
//enter name
System.out.print("Enter student "+(i+1)+" name: ");
name = reader.nextLine();
//enter quiz, assignment, test1 and test2 scores
//we also validate scores to not be negative
//and not out of bounds
do{
System.out.print("Enter Quiz Score (over 40): ");
quiz = Integer.parseInt(reader.nextLine());
if(quiz >= 0 && quiz <= 40){
break;
}else{
System.out.println("Please put a valid score.");
}
}while(true);
do{
System.out.print("Enter Assignment Score (over 30): ");
assign = Integer.parseInt(reader.nextLine());
if(assign >= 0 && assign <= 30){
break;
}else{
System.out.println("Please put a valid score.");
}
}while(true);
do{
System.out.print("Enter Midterm Test Score (over 55): ");
test1 = Integer.parseInt(reader.nextLine());
if(test1 >= 0 && test1 <= 55){
break;
}else{
System.out.println("Please put a valid score.");
}
}while(true);
do{
System.out.print("Enter Final Test Score (over 65): ");
test2 = Integer.parseInt(reader.nextLine());
if(test2 >= 0 && test2 <= 65){
break;
}else{
System.out.println("Please put a valid score.");
}
}while(true);
//after we get the name and student's score
//we put it in a string
studInfo[i] = name+ " " +quiz+ " " +assign+ " " +test1+ " " +test2;
System.out.println();
}
//return the studInfo
return studInfo;
}
//our displayGrade takes String array as parameter
public static void displayGrade(String[] studInfo){
//this is our header for our formatted table
System.out.println("================================================================================================================================================");
System.out.println(String.format("%-30s%-10s%-12s%-15s%-12s%-10s%-15s%s", "Name", "Quiz", "Assignment", "Midterm Test", "Final Test", "Average", "Letter Grade", "Status"));
System.out.println("================================================================================================================================================");
//we go through our array of string
for(int i = 0; i < studInfo.length; i++){
//the split method returns an array of strings
//that are split by a delimeter
String[] data = studInfo[i].split(" ");
//we sum up the scores
//but we have to parse it to double first
//to get the closest sum
double sum = ((Double.parseDouble(data[1]) / 40.0) * 100.0) * 0.15;
sum += ((Double.parseDouble(data[2]) / 30.0) * 100.0) * 0.15;
sum += ((Double.parseDouble(data[3]) / 55.0) * 100.0) * 0.3;
sum += ((Double.parseDouble(data[4]) / 65.0) * 100.0) * 0.4;
//after that we round the sum and convert it to int and put it in average
int average = (int) Math.round(sum);
char letterGrade = ' ';
//we get the letter grade using a nested if else
if(average>=0 && average<=59){
letterGrade = 'F';
}else if(average>=60 && average<=69){
letterGrade = 'D';
}else if(average>=70 && average<=79){
letterGrade = 'C';
}else if(average>=80 && average<=89){
letterGrade = 'B';
}else if(average>=90 && average<=100){
letterGrade = 'A';
}
String status = "";
//we determine the status of our student here
//using switch case
//if the leter grade is f then he fails
//if the case is D then he needs to go to remedial class
//otherwise they pass
switch(letterGrade){
case 'F':
status = "Fail";
break;
case 'D':
status = "Remedial";
break;
case 'A': case 'B': case 'C':
status = "Pass";
break;
}
//we displat student information
System.out.println(String.format("%-30s%-10s%-12s%-15s%-12s%-10d%-15c%s", data[0], data[1], data[2], data[3], data[4], average, letterGrade, status));
}
System.out.println("================================================================================================================================================");
}
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
displayGrade(getScores(reader, getNumStudents(reader)));
}
}
Instead of nextLine() you can use next("[0-9]+%?") and then remove the optional % character:
public static int getNumStudents(Scanner reader) {
int numStudents = 0;
//we get the number of students
do {
System.out.print("Enter number of students: ");
// Read the number either with or without the % sign
String input = reader.next("[0-9]+%?");
if (input.endsWith("%")) {
// Remove the % sign if present
input = input.substring(0, input.length() - 1);
}
numStudents = Integer.parseInt(input);
// we determine if the user input is valid
// it should be greater than 0
// because we don't want the number o students to be negative
// if it is not valid then we keep taking inputs
if (numStudents > 0) {
break;
}
System.out.println("Please enter at least 1 student.");
} while (true);
System.out.println("================================================================================================================================================");
// we return numStudents
return numStudents;
}

How to call a statement over and over again in Java

import java.util.*;
public class TestProject
{
public static void theMath()
{
double add = 1;
double subtract = 2;
double multiply = 3;
double divide = 4;
#SuppressWarnings("resource")
Scanner input = new Scanner(System.in);
//Pick first number
System.out.println("Please enter a number: ");
int intOne = input.nextInt();
// Pick second number
System.out.println("Please enter another number: ");
int intTwo = input.nextInt();
//User chooses operator
System.out.println("Now please choose an operator (1 for add, 2 for subtract, 3 for mulitply, 4 for divide): ");
int userChoice = input.nextInt();
// Add
if (userChoice == add)
System.out.println("Your answer is: " + (intOne + intTwo));
// Subtract
else if (userChoice == subtract)
System.out.println("Your answer is: " + (intOne - intTwo));
// Multiply
else if (userChoice == multiply)
System.out.println("Your answer is: " + (intOne * intTwo));
// Divide
else if (userChoice == divide)
System.out.println("Your answer is: " + (intOne / intTwo));
// If wrong input
else
{
System.out.println("Nothing happens!");
System.out.println("Please make sure you entered a number and an operator.");
}
}
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
theMath();
System.out.println("Would you like to do another calculation?");
String redo = input.nextLine();
if(redo.equals("yes"))
theMath();
else if(redo.equals("no"))
System.out.println("Thanks for calculating with me! It certainly was fun!");
else
System.out.println("Please enter 'yes' or 'no' only.");
String yesNo = input.nextLine();
if(yesNo.equals("yes"))
theMath();
else
System.out.println("Thanks for calculating with me! It certainly was fun!");
}
}
I was wondering how I could recall the main method an infinite amount of times if I wanted to. What I was doing was just copying and pasting it over and over again but there has to be a better way. And also, I would like to know how to return a value has a decimal(so I could do 25/6 and get the correct answer).
Why not put only the statements that should be repeated inside a loop?
String redo;
do{
System.out.println("Would you like to do another calculation?");
redo = input.nextLine();
if(redo.equals("yes"))
theMath();
else if(redo.equals("no"))
System.out.println("Thanks for calculating with me! It certainly was fun!");
else
System.out.println("Please enter 'yes' or 'no' only.");
String yesNo = input.nextLine();
if(yesNo.equals("yes"))
theMath();
else
System.out.println("Thanks for calculating with me! It certainly was fun!");
}while(redo.equals("yes"))
As for the other part of your question. If you have two int values and want to get a decimal from a division, you can do it like this:
int x = 2;
int y = 3;
double result = (double)x/y;
System.out.println(result);
This is called casting.

While loop with iteration

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

how to repeat loop based on user selection using scanner in java

Hi below is my Progarm
import java.util.Scanner;
public class Usecase1 {
public static void main(String[] args) {
Usecase1 us = new Usecase1();
us.withdrawl();
}
public void withdrawl() {
System.out.println("your Account number is....0091236452312");
System.out.println("please enter your pin number(1234)....");
Scanner sc = new Scanner(System.in);
int pinno = sc.nextInt();
if (pinno == 1234) {
System.out
.println("Please select type of Transaction 1.Balance Enquiry 2.Withdraw Money");
int option = sc.nextInt();
System.out.println("your choice is..." + option);
int totalamount = 85000;
if (option == 2) {
System.out.println("enter amount to withdraw");
int amount = sc.nextInt();
System.out.println("Remaining Balance in your account is..."
+ (totalamount - amount));
}
}
}
}
My requirement is to user can give his choice as 2 any number of times, for every time the below loop should be repeated please help me how to do this.
(option == 2) {
System.out.println("enter amount to withdraw");
int amount = sc.nextInt();
System.out.println("Remaining Balance in your account is..."
+ (totalamount - amount));
}
use while loop for that and a boolean to flag the loop
boolean isValid = true;
int totalamount = 85000;
while(isValid){
System.out.println("Please select type of Transaction 1.Balance Enquiry 2.Withdraw Money 3.Exit");
int option = sc.nextInt();
System.out.println("your choice is..." + option);
if (option == 2) {
System.out.println("enter amount to withdraw");
int amount = sc.nextInt();
System.out.println("Remaining Balance in your account is..."
+ (totalamount - amount));
} else if(option == 3){
//exit
isValid = false;
}
System.out.println("Do you want to continue? 1.yes 2.no");
int lastPrompt = sc.nextInt();
if(lastPrompt == 2){
break; or isValid = false;
}
}
use a while loop and
use break or continue to control over loop based on you condition.
eg-
while(true){
if (option == 2) {
System.out.println("enter amount to withdraw");
int amount = sc.nextInt();
System.out.println("Remaining Balance in your account is..."
+ (totalamount - amount));
}
else{
break;//break the loop
//or you may continue the loop
}
}
Replace the if(option == 2) with a while loop:
while (option == 2) {
System.out.println("enter amount to withdraw");
int amount = sc.nextInt();
System.out.println("Remaining Balance in your account is..." + (totalamount - amount));
//Stay in the loop if option is 2 again
option = sc.nextInt();
}
But if you want to consider more options, then use a flag like in the answers below

Categories