Continuity Issue in Java Calculator - java

I am new to Java, and I'm doing a calculator APP.
I'm trying to get my calculator to keep prompting the user for the correct answer (typing Y or N) after the else statement following 'Invalid Input'.
I want the program to continue with the calculations after the correct input is finally entered.
I have played around with an embedded while loop, but ended up with an infinite loop or a loop that terminates with no resolution. The code is below.
import java.util.Scanner;
class Calculate {
public static void.main(String[] args) {
System.out.println("Welcome To Calculator!");
System.out.println("*************************************************************************");
Scanner userinput = new Scanner(System.in);
double num1, num2;
String choice;
boolean youDecide = true;
while(youDecide == true) {
System.out.println("Please enter a number: ");
num1 = userinput.nextDouble();
System.out.println("Please enter an available operator (+, -, *, /): ");
char operator = userinput.next().charAt(0);
System.out.println("Please enter another number: ");
num2 = userinput.nextDouble();
double output;
switch(operator)
{
case '+':
output = num1 + num2;
break;
case '-':
output = num1 - num2;
break;
case '*':
output = num1 * num2;
break;
case '/':
output = num1 / num2;
if(num2 == 0)
System.out.println("Math error! A number cannot be divided by zero.");
break;
default:
System.out.println("Invalid input. Please enter an available operator, i.e (+, -, *, /): ");
return;
}
System.out.println("*************************************************************************");
System.out.println("The answer is: " + "\n" + output);
System.out.println("*************************************************************************");
System.out.println("Would you like to calculate again?");
System.out.println("Please enter Y for yes, or N for no");
choice = userinput.next();
if(choice.equalsIgnoreCase("Y")) {
System.out.println("Okay. Let's continue!");
System.out.println("*************************************************************************");
youDecide = true;
}
else if(choice.equalsIgnoreCase("N")) {
System.out.println("*************************************************************************");
System.out.println("Okay. Thanks for using Calculator. Goodbye!");
System.exit(0);
}
else {
System.out.println("Invalid input. Please try again...");
System.out.println("*************************************************************************");
youDecide = false;
}
}
}
}

I've made some changes and comments to your code
import java.util.Scanner;
class Calculator {
public static void main(String[] args) {
System.out.println("Welcome To Calculator!");
System.out.println("*************************************************************************");
Scanner userinput = new Scanner(System.in);
double num1, num2;
String choice;
//the "youDecide" variable is not needed at all
while (true) {
System.out.println("Please enter a number: ");
num1 = userinput.nextDouble();
System.out.println("Please enter an available operator (+, -, *, /): ");
char operator = userinput.next().charAt(0);
System.out.println("Please enter another number: ");
num2 = userinput.nextDouble();
double output;
switch (operator) {
case '+':
output = num1 + num2;
break;
case '-':
output = num1 - num2;
break;
case '*':
output = num1 * num2;
break;
case '/':
output = num1 / num2;
if (num2 == 0) {
System.out.println("Math error! A number cannot be divided by zero.");
}
break;
default:
System.out.println("Invalid input. Please enter an available operator, i.e (+, -, *, /): ");
continue; //changed from "return" you don't want to exit, just to skip to the next execution of the loop
}
System.out.println("*************************************************************************");
System.out.println("The answer is: " + "\n" + output);
System.out.println("*************************************************************************");
System.out.println("Would you like to calculate again?");
System.out.println("Please enter Y for yes, or N for no");
choice = userinput.next();
if (choice.equalsIgnoreCase("Y")) {
System.out.println("Okay. Let's continue!");
System.out.println("*************************************************************************");
} else if (choice.equalsIgnoreCase("N")) {
System.out.println("*************************************************************************");
System.out.println("Okay. Thanks for using Calculator. Goodbye!");
System.exit(0);
} else {
System.out.println("Invalid input. Please try again...");
System.out.println("*************************************************************************");
}
}
}
}

You need a while loop to ensure the value is correct.
Due the logic into your code you need to do when the user type the char, otherwise you have to change many lines of code, or ask for all values again.
I think for a begginer the easiest way is using this loop:
char operator;
while(true) {
operator = userinput.next().charAt(0);
if(operator=='+' || operator == '-' || operator == '*' || operator == '/') {
break;
}else {
System.out.println("Please enter a valid operator: ");
}
}
Exists many ways more elegant to do this. But I think for a begginer is the easiest way to understand and implement the code.
This loop is only to ensure the user type a valid character. While the character is not one of them, the loop will be iterating.
You have to place this code just below this line where you ask for a valid operator.

After adding the edits suggested by J.F. and Javaman along with some research, I was able to solve the problem by adding the following lines to my code:
import java.util.InputMismatchException;
import java.util.Scanner;
class Calculator {
public static void main(String[] args) {
System.out.println("Welcome To Calculator!");
System.out.println("*************************************************************************");
Scanner userinput = new Scanner(System.in);
char operator;
double num1, num2;
String choice;
while(true) {
System.out.println("Please enter a number: ");
num1 = userinput.nextDouble();
System.out.println("Please enter an available operator (+, -, *, /): ");
while(true) {
operator = userinput.next().charAt(0);
if(operator == '+' || operator == '-' || operator == '*' || operator == '/') {
break;
}else {
System.out.println("Invalid input. Please enter an available operator, i.e (+, -, *, /): ");
}
}
System.out.println("Please enter another number: ");
num2 = userinput.nextDouble();
double output;
switch(operator) {
case '+':
output = num1 + num2;
break;
case '-':
output = num1 - num2;
break;
case '*':
output = num1 * num2;
break;
case '/':
output = num1 / num2;
break;
default:
System.out.println("Invalid input. Please enter an available operator, i.e (+, -, *, /): ");
continue;
}
System.out.println("*************************************************************************");
if(num2 == 0) {
System.out.println("Math error! A number cannot be divided by zero.");
}else {
System.out.println("The answer is: " + "\n" + output);
}
System.out.println("*************************************************************************");
System.out.println("Would you like to calculate again?");
System.out.println("Please enter Y for yes, or N for no");
choice = userinput.next();
if(choice.equalsIgnoreCase("Y")) {
System.out.println("Okay. Let's continue!");
System.out.println("*************************************************************************");
}else if(choice.equalsIgnoreCase("N")) {
System.out.println("*************************************************************************");
System.out.println("Okay. Thanks for using Calculator. Goodbye!");
System.exit(0);
}else {
System.out.println("Invalid input. Please try again...");
System.out.println("*************************************************************************");
**while (!("Y").equalsIgnoreCase(choice) && !("N").equalsIgnoreCase(choice)) {
System.out.println("Invalid input. Please try again...");
System.out.println("*************************************************************************");
System.out.println("Please enter Y for yes, or N for no");
choice = userinput.next();
if(choice.equalsIgnoreCase("Y")) {
System.out.println("Okay. Let's continue!");
System.out.println("*************************************************************************");
}else if(choice.equalsIgnoreCase("N")) {
System.out.println("*************************************************************************");
System.out.println("Okay. Thanks for using Calculator. Goodbye!");
System.exit(0);**
}
}
}
}
}
}

Related

How to make this calculator to only accept numbers in first two input's and loop till they are correct

Somehow I got operator looping till I get correct input. When i try to put num1 or num2 in "if" statement, It says that I cannot convert "int" to "boolean". Please help
public class main {
public static void main(String[] args) {
int num1;
int num2;
String operator;
Scanner scan = new Scanner(System.in);
System.out.print("tell me first number: ");
num1 = scan.nextInt(); //<--input only numbers, loop if not
System.out.print("tell me second number: ");
num2 = scan.nextInt(); //<--input only numbers, loop if not
//////////////////operator////////////////////////
System.out.print("tell me operator: ");
operator = scan.next();
while(true) {
if(operator.equals("+")) {
System.out.println("answer is: " +(num1 + num2));
break;
}
else if(operator.equals("-")) {
System.out.println("answer is: " +(num1 - num2));
break;
}
else if(operator.equals("*")) {
System.out.println("answer is: " +(num1 * num2));
break;
}
else if(operator.equals("/")) {
System.out.println("answer is: " +(num1 / num2));
break;
}
else {
System.out.print("wrong input! try again!: ");
operator = scan.next();
}
}
}
}
Try this.
System.out.print("tell me first number: ");
while (!scan.hasNextInt()) scan.next();
num1 = scan.nextInt();
System.out.print("tell me second number: ");
while (!scan.hasNextInt()) scan.next();
num2 = scan.nextInt();
System.out.print("tell me first number: ");
while (!scan.hasNextInt()) scan.next();
num1 = scan.nextInt();
System.out.print("tell me second number: ");
while (!scan.hasNextInt()) scan.next();
num2 = scan.nextInt();
With this, wrong answer was looping till i got correct input, but I could not get it to print me "Wrong Input! Try again!: " with wrong input without starting to loop infinitely, so i tried to edit and came up with this.
//////////////////first number////////////////////
System.out.print("tell me first number: ");
while(!scan.hasNextInt()) {
System.out.print("Wrong Input! Try again!: "); scan.next();
if(scan.hasNextInt() == true) {
}
}
num1 = scan.nextInt();
//////////////////second number///////////////////
System.out.print("tell me second number: ");
while(!scan.hasNextInt()) {
System.out.print("Wrong input! Try again!: "); scan.next();
if(scan.hasNextInt() == true) {
}
}
num2 = scan.nextInt();
Somehow it helped lol.
Thanks #英語は苦手 for help.

java while loop with if/else statement, else argument runs forever instead of restarting while loop

So I have an assignment where I am supposed to prompt the user to enter an arithmetic operator, and then 2 numbers, and produce the result; i.e. user enters /, 20, 2 and the OUTPUT should be 10. I am using checks to ensure the proper value types are entered by the user, and my check for the integers entered runs forever if the else statement is activated. I am not sure where I am going wrong here. any guidance would be greatly appreciated.
import java.util.Scanner;
public class mainClass {
/**
* #param args the command line arguments
*/
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
boolean charCheck = true; //for verifying user arithmetic input
boolean numCheck = true; //for verifying user int input
boolean sysCheck = true; //for program outer while loop
int n1 = -1; //user entered number 1
int n2 = -2; //user entered number 2
char x = ' '; //user entered arithmetic operator
while (sysCheck == true)
{
while (charCheck == true)
{
System.out.println("Please enter either +, -, *, /to proceed. Enter x to end the program");
x = input.next().charAt(0);
switch(x) //check input validity for x before the program proceeds
{
case '+':
case '-':
case '*':
case '/':
System.out.println(x);
charCheck = false;
break;
case 'x':
System.exit(0);
break;
default:
System.out.print("That is an invalid entry. ");
}
}
System.out.println("Now, please enter 2 numbers, seperated by a space: ");
while(numCheck)
{
if(input.hasNextInt())
{
n1 = input.nextInt();
n2 = input.nextInt();
System.out.println(n1 + " " + n2);
numCheck = false;
}
else
System.out.print("That is an invalid entry. ");
}
switch(x) //check input validity for x before the program proceeds
{
case '+':
System.out.print("The result is: " + (n1 + n2));
break;
case '-':
System.out.print("The result is: " + (n1 - n2));
break;
case '*':
System.out.print("The result is: " + (n1 * n2));
break;
case '/':
System.out.print("The result is: " + (n1 / n2));
break;
}
}
}
}
After playing around with the code more and researching more, I found the solution. the issue I was having was due to not including the line
input.next(); in my else statement (input is the name of my scanner, if you named your scanner something else, that name would be in it's place)
while(numCheck)
{
System.out.println("Now, please enter 2 numbers, seperated by a space: ");
if(!input.hasNextInt())
{
System.out.println("That is an invalid entry. ");
input.next();
}
else
{
n1 = input.nextInt();
n2 = input.nextInt();
numCheck = false;
}
}

How to store value in calc and continue counting?

How to modify the code so I can continuously count? So for example 2+3=5, and than -1 =4, until i press q to exit program ?? Please some simple solution for beginners. Thank you.
import java.util.Objects;
import java.util.Scanner;
public class Calc {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
do {
System.out.println("Enter first number:");
double num1 = sc.nextDouble();
System.out.println("Enter second number");
double num2 = sc.nextDouble();
System.out.println("Select operator (+,-,*,/) or enter q to exit:");
char operator = sc.next().charAt(0);
switch (operator) {
case '+':
System.out.println("Result =" + Equasion.sum(num1, num2));
break;
case '-':
System.out.println(Equasion.substract(num1, num2));
break;
case'/':
if (num2 == 0) {
System.out.println("Divide by zero problem");
} else System.out.println(Equasion.divide(num1, num2));
case '*':
System.out.println(Equasion.multiply(num1, num2));
break;
case 'q':
System.exit(0);
}
System.out.println("Press any key to continue or q to quit");
} while (!Objects.equals(ExitProg.exitProg(), 'q'));
}
}
Correct me if I'm wrong but you should move the first lines outside the while loop then overwrite the values of num1 and num2 every iteration (num2 becomes num1, then the user inputs another num2)

Why is my programming not looping correctly? (Java)

Desired output: Hello, I am trying to make a program that does addition, subtraction, multiplication, and division and loops until you press 'e' to exit the loop.
So, I want it to look something like this:
A. Addition
B. Subtraction
C. Multiplication
D. Division
E. Exit
Please enter your selection, enter E to end:
//let's say they enter a, and want to add 5 plus 5
Enter your first number:
Enter your second number:
5 + 5 = 10.0
Please enter your selection, enter E to end:
//This looping part is what I want to happen! But my program just ends, and I'm not
sure how to fix it
Issue: My problem is that once you enter what operation you want, it only does the arithmetic once and then it displays my exit message and ends, but that is only supposed to happen when the user enters 'e' but the rest works, I think!
Here is my code
import java.util.Scanner;
public class Calculator_Loop {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner input = new Scanner(System.in);
char selection;
char choice = 'E';
double num_1;
double num_2;
double result;
System.out.println("A. Addition\nB. Subtraction\nC. Multiplication\nD. Division \n\nE. Exit");
//System.out.println("\nPlease enter your selection, enter E to end:");
//selection = input.next().charAt(0);
//choice = Character.toUpperCase(selection);
while(choice != 'E')
System.out.println("\nPlease enter your selection, enter E to end:");
selection = input.next().charAt(0);
choice = Character.toUpperCase(selection);
if(choice == 'A') {
System.out.println("Enter your first number:");
num_1 = input.nextDouble();
System.out.println("Enter your second number:");
num_2 = input.nextDouble();
result = num_1 + num_2;
System.out.println(result);
}
if(choice == 'B'){
System.out.println("Enter your first number:");
num_1 = input.nextDouble();
System.out.println("Enter your second number:");
num_2 = input.nextDouble();
result = num_1 - num_2;
System.out.println(result);
}
if(choice == 'C'){
System.out.println("Enter your first number:");
num_1 = input.nextDouble();
System.out.println("Enter your second number:");
num_2 = input.nextDouble();
result = num_1 * num_2;
System.out.println(result);
}
if(choice == 'D'){
System.out.println("Enter your first number:");
num_1 = input.nextDouble();
System.out.println("Enter your second number:");
num_2 = input.nextDouble();
result = num_1 / num_2;
System.out.println(result);
}
System.out.println("Thank you, have a nice day!");
}
}
Am I doing something wrong with the brackets? Or is there something I'm missing for the loop to work? Any help is appreciated, thanks!
Welcome to SO.
Problem is (as far as I can see) that you have nothing/only the print line in your while loop.
while(true) {
do things
}
Java allows while loops without brackets, but at maximum one line (and I recommend doing them for one line too, but that is debattable), as soon as you need several lines, you need brackets and should have according indentation.
You need to surround your intended while loop with brackets to make it work the way you want:
while (choice != 'E') {
System.out.println("\nPlease enter your selection, enter E to end:");
selection = input.next().charAt(0);
choice = Character.toUpperCase(selection);
switch (choice) {
case 'A':
System.out.println("Enter your first number:");
num_1 = input.nextDouble();
System.out.println("Enter your second number:");
num_2 = input.nextDouble();
result = num_1 + num_2;
System.out.println(result);
break;
case 'B':
// ...
}
}
System.out.println("Thank you, have a nice day!");
Currently, your while loop will spin forever (I think), because the seed value for choice is being set to E.
Side note: Consider using a switch statement to handle the various case values for the choice.
Instead of using the if conditions, please use the while loop and switch condition. if the input value is other than the A, B, C or D then exit from the code.
Code takes only the first character of your input and enters into switch case, where it will compare the input with the required conditions.
public class Calculator_Loop {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String choice = "";
double num_1;
double num_2;
double result;
System.out.println("A. Addition\nB. Subtraction\nC. Multiplication\nD. Division \n\nE. Exit");
/*System.out.println("\nPlease enter your selection, enter E to end:");
selection = input.next().charAt(0);
choice = input.next().substring(0, 1).toUpperCase();*/
outer: while (true) {
System.out.println("\nPlease enter your selection, enter E to end:");
choice = input.next();
choice = choice.substring(0, 1).toUpperCase();
switch (choice) {
case "A":
System.out.println("Enter your first number:");
num_1 = input.nextDouble();
System.out.println("Enter your second number:");
num_2 = input.nextDouble();
result = num_1 + num_2;
System.out.println(result);
break;
case "B":
System.out.println("Enter your first number:");
num_1 = input.nextDouble();
System.out.println("Enter your second number:");
num_2 = input.nextDouble();
result = num_1 - num_2;
System.out.println(result);
break;
case "C":
System.out.println("Enter your first number:");
num_1 = input.nextDouble();
System.out.println("Enter your second number:");
num_2 = input.nextDouble();
result = num_1 * num_2;
System.out.println(result);
break;
case "D":
System.out.println("Enter your first number:");
num_1 = input.nextDouble();
System.out.println("Enter your second number:");
num_2 = input.nextDouble();
result = num_1 / num_2;
System.out.println(result);
break;
default:
System.out.println("Thank you, have a nice day!");
break outer;
}
}
}
}
You class has two problems.
One is the missing brace that others metioned.
The other is that it will never enter the loop as the condition is allways false.
So to make sure that the loop is entered at least once you need an endcondition. a do-while construct instead of your startcondition.
So I changed your while loop into a do-while. By that I added the missing curly.
I also changed your if's to a switch as a choice calls for it.
And I moved the question into the loop, so the user gets the information in every iteration.
import java.util.Scanner;
public class Calculator_Loop {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner input = new Scanner(System.in);
char selection;
char choice = 'E';
double num_1;
double num_2;
double result;
do {
System.out.println("A. Addition\nB. Subtraction\nC. Multiplication\nD. Division \n\nE. Exit");
//System.out.println("\nPlease enter your selection, enter E to end:");
//selection = input.next().charAt(0);
//choice = Character.toUpperCase(selection);
System.out.println("\nPlease enter your selection, enter E to end:");
selection = input.next().charAt(0);
choice = Character.toUpperCase(selection);
switch (choice) {
case 'A':
System.out.println("Enter your first number:");
num_1 = input.nextDouble();
System.out.println("Enter your second number:");
num_2 = input.nextDouble();
result = num_1 + num_2;
System.out.println(result);
break;
case 'B':
System.out.println("Enter your first number:");
num_1 = input.nextDouble();
System.out.println("Enter your second number:");
num_2 = input.nextDouble();
result = num_1 - num_2;
System.out.println(result);
break;
case 'C':
System.out.println("Enter your first number:");
num_1 = input.nextDouble();
System.out.println("Enter your second number:");
num_2 = input.nextDouble();
result = num_1 * num_2;
System.out.println(result);
break;
case 'D':
System.out.println("Enter your first number:");
num_1 = input.nextDouble();
System.out.println("Enter your second number:");
num_2 = input.nextDouble();
result = num_1 / num_2;
System.out.println(result);
break;
}
} while (choice != 'E');
System.out.println("Thank you, have a nice day!");
}
}

Simple calculator program in Java

I am a newbie coder in Java and I am trying to make this calculator in java where a user can enter two numbers and select the operation to be done on those numbers. However when the code comes to selecting the operator it skips the user input and the if statement and directly implements the else statement.
import java.util.Scanner;
public class Calculator {
public static void main(String[] args) {
Scanner Calc = new Scanner(System.in);
int n1;
int n2;
int Answer;
System.out.println("Enter the first number: ");
n1 = Calc.nextInt();
System.out.println("Enter the second number:" );
n2 = Calc.nextInt();
System.out.println("Select the order of operation: ");
char operator = Calc.nextLine().charAt(0);
if (operator == '+') {
Answer = (n1 + n2);
System.out.println("Answer:" + Answer);
}
if (operator == '-') {
Answer = (n1 - n2);
System.out.println("Answer:" + Answer);
}
if (operator == '*') {
Answer = (n1 * n2);
System.out.println("Answer:" + Answer);
}
if (operator == '/') {
Answer = (n1/n2);
System.out.println("Answer:" + Answer);
}
else {
System.out.println("not implemented yet. Sorry!");
}
}
}
Add Calc.nextLine(); after n2 = Calc.nextInt(); to consume the line feed.
You are also not using else if so all those if conditions will be checked even if previous if already matched (resulting in your final else being executed as long as operator not '/').
In this case you should probably just use a switch block.
I made some changes to the code, this should work with you, but I also recommend using a switch.
Scanner Input = new Scanner(System.in);
try {
System.out.print("Enter a number: ");
int num1 = Input.nextInt();
System.out.print("Enter an operator: ");
char operator = Input.next().charAt(0);
System.out.print("Enter a second number: ");
int num2 = Input.nextInt();
// this part of decision, it doesn't work.
if ('+' == operator) {
System.out.println("Your result is " + (num1 + num2));
} else if ('-' == operator) {
System.out.println("Your result is " + (num1 - num2));
} else if ('*' == operator) {
System.out.println("Your result is " + (num1 * num2));
} else if ('/' == operator) {
System.out.println("Your result is " + (num1 / num2));
}else {
System.out.println("Your answer is not valid");
}
} catch (InputMismatchException e) {
System.out.println("similar to try and except in Python");
}

Categories

Resources