How to call a statement over and over again in Java - 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.

Related

Java program reading indefinite amount of numbers from a user till a positive is entered

I need to write a java program reading in an indefinite amount of numbers and saves them to a collection of numbers, until an (even number) is entered in by the user. I have tried with a while loop, that when a positive number is found in it it stops. But it is not really working. Here is codes I have tried:
public static void main(String[] args) {
int programInteger = 1;
int inputtedInteger;
while (programInteger < 2) {
System.out.println("Enter a number: "); //Asks user to input a number
Scanner in = new Scanner(System.in);
inputtedInteger = Scanner(in.nextLine);
if (inputtedInteger != 0) {
System.out.println("The number "+ inputtedInteger +" that you inputted is not an even number, try again: ");
inputtedInteger=in.nextInt();
}
else if (inputtedInteger % 2 == 0){
programInteger =+1;
System.out.println("The number "+inputtedInteger+" that you entered is an even number!");
}
}
}
/* if(inputtedInteger % 2 == 0) {
System.out.println("The number "+ inmatatTal +" you entered is an even number!");
}
else {
System.out.println("Enter a number?! ");
inputtedInteger = in.nextInt();
}
Fixing a few things in the logic of the loop should work:
int inputtedInteger = 0;
Scanner in = new Scanner(System.in);
while (inputtedInteger < 1) {
System.out.println("Enter a number: "); //Asks user to input a number
inputtedInteger = in.nextInt();
if (inputtedInteger % 2 != 0) {
System.out.println("The number "+ inputtedInteger +" that you inputted is not an even number, try again: ");
}
else if (inputtedInteger % 2 == 0){
System.out.println("The number "+inputtedInteger+" that you entered is an even number!");
}
}
I would setup an outline for the code like this:
setup Scanner, create collection
while true:
userInput = scanner.nextInt()
if userInput > 0: break
collection.add(userInput)
print('user entered', collection.length(), 'numbers.')
Hope that helps. I'll leave you to fill this using actual Java syntax.
I wrote a comment on the OP on why your structure is failing to solve the issue at hand.

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

while loop keeps ending without initiating the if-statement

I'm trying to create a simple calculator program on Java as a simple first project as I learn Java.
Problem: After I run the program and after doing my calculation, I wanted to give the user the option on whether they want to end the program or do some more calculations. for some reason the program is not using the (if) statements that I have placed in it, it seems to skip it and end my program without allowing the user to input his choice at the end.
I'm really sorry if my question is not clear, I couldn't find a solution for my problem online, and I do apologize if my code looks really messy.
import java.util.Scanner;
public class Calculator {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
double fnum, snum, answer;
String choice, name, in;
System.out.println("Hello, whats your name?");
name = input.nextLine();
System.out.println("");
System.out.println("Oh so your name is " + name + "!");
System.out.println("");
System.out.println("This program is a calculator that will do simple calculation of two numbers");
System.out.println("There are four different options to choose from:");
boolean running = true;
CAL:
while (running) {
System.out.println("type a for Addition, b for subtraction, c for multiplication and d for division");
System.out.println("Then press enter!");
choice = input.nextLine();
while (!choice.equals("a") &&
!choice.equals("A") &&
!choice.equals("b") &&
!choice.equals("B") &&
!choice.equals("c") &&
!choice.equals("C") &&
!choice.equals("d") &&
!choice.equals("D")) {
System.out.println("Wrong choice, Please try again");
System.out.println("type a for Addition, b for subtraction, c for multiplication and d for division");
choice = input.nextLine();
}
if (choice.equals("a") || choice.equals("A")) {
System.out.println(name +" You have chosen Addition");
System.out.println("Type the first number:");
fnum = input.nextDouble();
System.out.println("Type the second number:");
snum = input.nextDouble();
System.out.println("your answer is:");
Addition addy = new Addition(fnum,snum);
System.out.println(addy.getans());
}
if (choice.equals("b") || choice.equals("B")) {
System.out.println(name +" You have chosen Subtraction");
System.out.println("Type the first number:");
fnum = input.nextDouble();
System.out.println("Type the second number:");
snum = input.nextDouble();
answer = fnum - snum;
System.out.println("your answer is:"
+ answer);
}
if (choice.equals("c") || choice.equals("C")) {
System.out.println(name +" You have chosen Multiplication");
System.out.println("Type the first number:");
fnum = input.nextDouble();
System.out.println("Type the second number:");
snum = input.nextDouble();
answer = fnum * snum;
System.out.println("your answer is:"
+ answer);
}
if (choice.equals("d") || choice.equals("D")) {
System.out.println(name +" You have chosen Addition");
System.out.println("Type the first number:");
fnum = input.nextDouble();
while (fnum == 0) {
System.out.println("invalid try again!");
fnum = input.nextDouble();
}
System.out.println("Type the second number:");
snum = input.nextDouble();
answer = fnum / snum;
System.out.println("your answer is:"
+ answer);
}
System.out.println("");
System.out.println("Thank you " + name + " for using this simple calculator :)");
System.out.println("If you would like to try again press a the press Enter, if you wish to exit press any botton and then press enter");
in = input.nextLine();
if (in.equals("a")) {
System.out.println("");
System.out.println("Thank you, please choose again");
System.out.println("");
} else {
System.out.println("Thank you and goodbye");
break;
}
}
}
}
It's a simple problem caused by nextInt/Double/etc behaviour.
Those methods don't read the following new-line character so the next nextLine will always return an empty string (the rest of the current line).
Try to change those (e.g. the addition case) with Double.parseDouble(input.nextLine());
if (choice.equals("a") || choice.equals("A")) {
System.out.println(name + " You have chosen Addition");
System.out.println("Type the first number:");
fnum = Double.parseDouble(input.nextLine());
System.out.println("Type the second number:");
snum = Double.parseDouble(input.nextLine());
System.out.println("your answer is:");
Addition addy = new Addition(fnum, snum);
System.out.println(addy.getans());
}
you can notice debugging that the last in = input.nextLine(); called to ask for user input will always be empty string.

Wrong Quiz result

This is the output of the program
I was able to do till to get this result by doing this program below
import java.util.Scanner;
public class aLittleQuiz {
public static void main(String[] args) {
// declaring varibles
String quizStart;
int quizAns1, quizAns2, quizAns3;
Scanner input = new Scanner(System.in);
System.out.println("Are you ready for a quiz? (y / n)");
quizStart = input.next();
System.out.println("Okay, here it comes!");
// quiz answer 1
System.out.println("\nWhat is the capital of Alaska? \n1) Melbourne\n2) Anchorage\n3) Juneau");
quizAns1 = input.nextInt();
if (quizAns1 == 3) {
System.out.println("That's right");
} else {
System.out.println("Your answer is wrong, sorry!");
}
// quiz answer 2
System.out.println("Q2) Can you store the value ''cat'' in a variable of type int? \n1) yes \n2) no");
quizAns2 = input.nextInt();
if (quizAns2 == 1) {
System.out.println("Sorry, ''cat'' is a string. ints can only store numbers.");
} else if (quizAns2 == 2) {
System.out.println("Correct!");
}
// quiz answer 3
System.out.println("What is the result of 9+6/3? \n1) 5\n2) 11 \n3) 15/3");
quizAns3 = input.nextInt();
if (quizAns3 == 2) {
System.out.println("That's correct!");
} else {
System.out.println("");
}
// if (quizAns == 3 && quizAns == ) {
// }
}
}
but how I can program this part?
"Overall, you got 2 out of 3 correct.
Thanks for playing!"
Declare a variable like int marks and increment it by one inside if\else block(which made for correct answer). And at the end print
System.out.println("Overall, you got" +marks+" out of 3 correct. Thanks for playing!");
Assuming your no of question is fixed( 3 )
String quizStart;
int quizAns1, quizAns2, quizAns3;
int marks=0;
Scanner input = new Scanner(System.in);
System.out.println("Are you ready for a quiz? (y / n)");
quizStart = input.next();
System.out.println("Okay, here it comes!");
// quiz answer 1
System.out.println("\nWhat is the capital of Alaska? \n1) Melbourne\n2) Anchorage\n3) Juneau");
quizAns1 = input.nextInt();
if (quizAns1 == 3) {
System.out.println("That's right");
++marks;
} else {
System.out.println("Your answer is wrong, sorry!");
}
// quiz answer 2
System.out.println("Q2) Can you store the value ''cat'' in a variable of type int? \n1) yes \n2) no");
quizAns2 = input.nextInt();
if (quizAns2 == 1) {
System.out.println("Sorry, ''cat'' is a string. ints can only store numbers.");
} else if (quizAns2 == 2) {
System.out.println("Correct!");
++marks;
}
// quiz answer 3
System.out.println("What is the result of 9+6/3? \n1) 5\n2) 11 \n3) 15/3");
quizAns3 = input.nextInt();
if (quizAns3 == 2) {
System.out.println("That's correct!");
++marks;
} else {
System.out.println("");
}
System.out.println("Overall, you got " +marks+" out of 3 correct. Thanks for playing!");

How to implement a for loop inside a while loop?

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

Categories