validating char user input loop - java

I'm writing a simple calculator program, the user inputs two integers and a symbol (+ - * etc) which represents the operation (add, subtract, multiply, etc) to be applied to the integers and the program calculates what they asked.
I have a do-while loop to continually ask for input if the input does not match the given symbols.
I've tried comparing them but I'm unsuccessful and very uncertain on what to do
CODE:
Scanner scan = new Scanner(System.in);
int num1, num2, sum, difference, product;
String a, b, c, userInput;
char choice, plus, minus, times;
System.out.print(First Integer: --> ");
num1 = scan.nextInt();
System.out.print(Second Integer: --> ");
num2 = scan.nextInt();
a = "+";
b = "-";
c = "*";
plus = a.charAt(0);
minus = b.charAt(0);
times = c.charAt(0);
do {
System.out.print("Choose + - or *");
userInput = scan.Next();
choice = userInput.charAt(0);
} while(choice != '+' || choice != '-' || choice != '*');
switch(choice) {
case 1:
sum = num1 + num2;
System.out.println("Sum is " + sum);
break;
case 2:
difference = num1 - num2;
System.out.println("Difference is " + difference);
break;
case 3:
product = num1 ' num2;
System.out.println("Product is " + product);
break;
}

There were some errors in your code, I have tried to rectify them.
Take a look,
public class Main {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int num1, num2, sum, difference, product;
String userInput;
char choice, plus, minus, times;
System.out.println("First Integer: --> ") ;
num1 = scan.nextInt();
System.out.println("Second Integer: --> ") ;
num2 = scan.nextInt();
plus = '+';
minus = '-';
times = '*';
do {
System.out.println("Choose + - or *") ;
userInput = scan.next();
choice = userInput.charAt(0);
}while(choice != '+' && choice != '-' && choice != '*');
switch(choice) {
case '+':
sum = num1 + num2;
System.out.println("Sum is " + sum);
break;
case '-':
difference = num1 - num2;
System.out.println("Difference is " + difference);
break;
case '*':
product = num1 * num2;
System.out.println("Product is " + product);
break;
default :
System.out.println("Wrong Choice!");
break;
}
}
}

Related

Java Calculator program issue

I am trying to develop a calculator program that inputs an arithmetic expression of the form number operator number = and computes the result of the expression. The expression will be evaluated from left to right not considering regular operator precedence. For example, the expression 14 - 5 * 3 = will produce 27.0. The value = displays the final result and terminates the program.
I've been trying to fix this for a couple of days now, but it outputs the wrong answer whenever I enter an expression with more than two numbers. For instance, 2.8 + 2 - 9.5 should equal -4.7 but the program outputs -6.7. Any idea why that is the case?
import java.util.Scanner;
public class Calculator {
// Compute an arithmetic expression
public static void main(String[] args) {
// Declare the identifiers
final String END = "=";
String input;
double num1 = 0;
double num2 = 0;
char operator = 0;
Scanner scnr = new Scanner (System.in);
System.out.println("Enter your numeric expression in the following form: ");
System.out.println("number operator number operator number = ");
System.out.println("Leave a blank space after each number or operator.");
System.out.println("Example: 3.5 * 3 - 5 / 2.5 =");
// Input the first item
System.out.print("> ");
input = scnr.next();
// Process the first item and input and process the rest of the items
while (!input.equals(END)){
switch (input){
case "+":
operator = '+';
System.out.println("> Operator is: " + operator);
break;
case "-":
operator = '-';
System.out.println("> Operator is: " + operator);
break;
case "*":
operator = '*';
System.out.println("> Operator is: " + operator);
break;
case "/":
operator = '/';
System.out.println("> Operator is: " + operator);
break;
default: // a number was entered
if (num1 == 0) {
num1 = Double.parseDouble(input);
System.out.println("> Num1 is: " + num1);
}
else {
num2 = Double.parseDouble(input);
System.out.println("> Num2 is: " + num2);
}
} // end of switch
if (num1 != 0 && num2 != 0) {
System.out.println("Num2 before calc is " + num2);
switch (operator) {
case '+':
num2 = num1 + num2;
break;
case '-':
num2 = num1 - num2;
break;
case '*':
num2 = num1 * num2;
break;
case '/':
num2 = num1 / num2;
break;
default:
}
}
input = scnr.next();
} // end of while-loop
// Display the answer
System.out.println("> Answer is: " + num2);
System.out.println("Have a nice day!");
}
}
In order to make it work, try to:
in your 2nd switch statement, change num2 = num1 + num2; into num1 = num1 + num2;. Do this for all cases;
I added an isOperator boolean to skip computing the operation if input is an operator.
Full code below:
import java.util.Scanner;
public class Calculator {
// Compute an arithmetic expression
public static void main(String[] args) {
// Declare the identifiers
final String END = "=";
String input;
double num1 = 0;
double num2 = 0;
char operator = 0;
boolean isOperator;
Scanner scnr = new Scanner (System.in);
System.out.println("Enter your numeric expression in the following form: ");
System.out.println("number operator number operator number = ");
System.out.println("Leave a blank space after each number or operator.");
System.out.println("Example: 3.5 * 3 - 5 / 2.5 =");
// Input the first item
System.out.print("> ");
input = scnr.next();
// Process the first item and input and process the rest of the items
while (!input.equals(END)){
isOperator = true;
switch (input){
case "+":
operator = '+';
System.out.println("> Operator is: " + operator);
break;
case "-":
operator = '-';
System.out.println("> Operator is: " + operator);
break;
case "*":
operator = '*';
System.out.println("> Operator is: " + operator);
break;
case "/":
operator = '/';
System.out.println("> Operator is: " + operator);
break;
default: // a number was entered
isOperator = false;
if (num1 == 0) {
num1 = Double.parseDouble(input);
System.out.println("> Num1 is: " + num1);
}
else {
num2 = Double.parseDouble(input);
System.out.println("> Num2 is: " + num2);
}
} // end of switch
// do not compute the operation if the input is an operator and num1,num2 != 0
if (num1 != 0 && num2 != 0 && !isOperator) {
System.out.println("Num2 before calc is " + num2);
switch (operator) {
case '+':
num1 = num1 + num2;
break;
case '-':
num1 = num1 - num2;
break;
case '*':
num1 = num1 * num2;
break;
case '/':
num1 = num1 / num2;
break;
default:
}
}
input = scnr.next();
} // end of while-loop
// Display the answer
System.out.println("> Answer is: " + num1);
System.out.println("Have a nice day!");
}
}
Edit: As mentioned in the comments, the code does not treat the cases when the user inputs 0. Below, I removed the if(num1 == 0) and if (num1 != 0 && num2 != 0) conditions:
import java.util.Scanner;
public class Calculator {
// Compute an arithmetic expression
public static void main(String[] args) {
// Declare the identifiers
final String END = "=";
String input;
double result = 0;
double num = 0;
char operator = 0;
boolean isOperator;
Scanner scnr = new Scanner (System.in);
System.out.println("Enter your numeric expression in the following form: ");
System.out.println("number operator number operator number = ");
System.out.println("Leave a blank space after each number or operator.");
System.out.println("Example: 3.5 * 3 - 5 / 2.5 =");
// Input the first item
System.out.print("> ");
input = scnr.next();
// Process the first item and input and process the rest of the items
while (!input.equals(END)){
isOperator = true;
switch (input){
case "+":
operator = '+';
System.out.println("> Operator is: " + operator);
break;
case "-":
operator = '-';
System.out.println("> Operator is: " + operator);
break;
case "*":
operator = '*';
System.out.println("> Operator is: " + operator);
break;
case "/":
operator = '/';
System.out.println("> Operator is: " + operator);
break;
default: // a number was entered
isOperator = false;
num = Double.parseDouble(input);
System.out.println("> Num is: " + num);
} // end of switch
// do not compute the operation if the input is an operator
if (!isOperator) {
System.out.println("Result before calc is " + result);
switch (operator) {
case '+':
result += num;
break;
case '-':
result -= num;
break;
case '*':
result *= num;
break;
case '/':
result /= num;
break;
default:
result += num;
}
}
input = scnr.next();
} // end of while-loop
// Display the answer
System.out.println("> Answer is: " + result);
System.out.println("Have a nice day!");
}
}
I switched up your order a little bit and reset the holding variable.
public static void main(String[] args) {
// Declare the identifiers
final String END = "=";
String input;
double num1 = 0;
double num2 = 0;
char operator = 0;
Scanner scnr = new Scanner (System.in);
System.out.println("Enter your numeric expression in the following form: ");
System.out.println("number operator number operator number = ");
System.out.println("Leave a blank space after each number or operator.");
System.out.println("Example: 3.5 * 3 - 5 / 2.5 =");
// Input the first item
System.out.print("> ");
input = scnr.next();
// Process the first item and input and process the rest of the items
while (!input.equals(END)){
switch (input){
case "+":
operator = '+';
System.out.println("> Operator is: " + operator);
break;
case "-":
operator = '-';
System.out.println("> Operator is: " + operator);
break;
case "*":
operator = '*';
System.out.println("> Operator is: " + operator);
break;
case "/":
operator = '/';
System.out.println("> Operator is: " + operator);
break;
default: // a number was entered
if (num1 == 0) {
num1 = Double.parseDouble(input);
System.out.println("> Num1 is: " + num1);
} else {
num2 = Double.parseDouble(input);
System.out.println("> Num2 is: " + num2);
}
} // end of switch
if (num1 != 0 && num2 != 0) {
System.out.println(String.format("Num1 : %.3f, Num2: %.3f", num1, num2));
switch (operator) {
case '+':
num1 = num1 + num2;
num2 = 0;
break;
case '-':
num1 = num1 - num2;
num2 = 0;
break;
case '*':
num1 = num1 * num2;
num2 = 0;
break;
case '/':
num1 = num1 / num2;
num2 = 0;
break;
default:
}
}
input = scnr.next();
} // end of while-loop
// Display the answer
System.out.println("> Answer is: " + num1);
}

Java Calculator Switch Issue

I incorporated a couple different methods I've seen on here. Does anyone know how to fix this problem I am having? When you use this code, It asks for you to enter the mathematical operator, BUT when I do if I enter +9 or -%, it will still work and use the first symbol. I want it to give an error if someone inputs */ instead of just *. I even tried switching the case to numbers (ie case 1:) and it will do the same thing if I set addition to 1 and if I enter 15, it will read the one and do addition. Any ideas?
import java.util.Scanner;
public class javacalculator {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
Scanner operation = new Scanner(System.in);
double num1, num2, answer;
char userOperation;
System.out.print("Enter your full name: ");
String userName = input.nextLine();
System.out.println("+ Addition");
System.out.println("- Subtraction");
System.out.println("* Multiplication");
System.out.println("/ Division");
System.out.println("% Modulus");
System.out.println("\n");
System.out.print("Enter mathematical operator e.g. + for Addition: ");
userOperation = operation.next().charAt(0);
boolean invalidOperator = false;
switch (userOperation) {
case '+':
System.out.print("Enter first number: ");
num1 = input.nextInt();
System.out.print("Enter the second number: ");
num2 = input.nextInt();
answer = num1 + num2;
System.out.print(num1 + " + " + num2 + " = " + answer);
break;
case '-':
System.out.print("Enter first number: ");
num1 = input.nextInt();
System.out.print("Enter the second number: ");
num2 = input.nextInt();
answer = num1 - num2;
System.out.print(num1 + " - " + num2 + " = " + answer);
break;
case '*':
System.out.print("Enter first number: ");
num1 = input.nextInt();
System.out.print("Enter the second number: ");
num2 = input.nextInt();
answer = num1 * num2;
System.out.print(num1 + " * " + num2 + " = " + answer);
break;
case '/':
System.out.print("Enter first number: ");
num1 = input.nextInt();
System.out.print("Enter the second number: ");
num2 = input.nextInt();
answer = num1 / num2;
System.out.print(num1 + " / " + num2 + " = " + answer);
break;
case '%':
System.out.print("Enter first number: ");
num1 = input.nextInt();
System.out.print("Enter the second number: ");
num2 = input.nextInt();
answer = num1 % num2;
System.out.print(num1 + " % " + num2 + " = " + answer);
break;
default:
System.out.println("Invalid operator!");
break;
}
}
}
Let us break this down: operation.next().charAt(0);
operation.next() -> Gives you full input string
.charAt(0); -> returns the first character of the full input string
So anything we enter +9 or */ -> it returns the first element.
Now let's handle this case:
String o = operation.next(); // here is complete input
if(o.length()!=1){
userOperation = 0; //if length of input is not 1 we set custom value
}else{
userOperation = o.charAt(0); //get and set the first and only element
}
Hopefully it helps!

Not getting the expected output from the do-while loop

In this calculator program when I type in any other incorrect answer for the operator such as a number or a letter instead of +, -, *, / it shows the "wrong only operators" message but even when I put in the correct operator the same message still shows up.
How can the program not show the wrong message when I type in the correct symbol.
import java.util.Scanner;
public class Main {
public static void main(String[] args)
{
double num1, num2;
double output = 0;
char operator;
Scanner scan = new Scanner (System.in);
System.out.println("Type in first number ");
while(scan.hasNextDouble() == false)
{
System.out.println("Wrong only numbers. ");
scan.nextLine();
}
num1 = scan.nextDouble();
System.out.println("Type in the operator ");
do
{
operator = scan.next().charAt(0);
System.out.println("Wrong only operators. ");
scan.nextLine();
}
while(operator != '+' && operator != '-' && operator != '*' && operator != '/');
System.out.println("Type in second number ");
while(scan.hasNextDouble() == false)
{
System.out.println("Wrong only numbers. ");
scan.nextLine();
}
num2 = scan.nextDouble();
switch (operator)
{
case '+': output = num1 + num2; break;
case '-': output = num1 - num2; break;
case '*': output = num1 * num2; break;
case '/': output = num1 / num2; break;
}
System.out.println("" + num1 + " " + operator + " " + num2 + " = " + output);
}
}
In your case it is better to use a while loop instead of a do while.
Since you are using a do while loop : that statement is being executed at least once, not matter whether the operator is correct or not.
You can add a condition there to stop it from executing but a better way is to use while loop
import java.util.Scanner;
class Main {
public static void main(String[] args)
{
double num1, num2;
double output = 0;
char operator;
Scanner scan = new Scanner(System.in);
System.out.println("Type in first number ");
while(scan.hasNextDouble() == false)
{
System.out.println("Wrong only numbers. ");
scan.nextLine();
}
num1 = scan.nextDouble();
System.out.println("Type in the operator ");
operator = scan.next().charAt(0);
while(operator != '+' && operator != '-' && operator != '*' && operator != '/')
{
System.out.println("Wrong only operators. ");
operator = scan.next().charAt(0);
scan.nextLine();
}
System.out.println("Type in second number ");
while(scan.hasNextDouble() == false)
{
System.out.println("Wrong only numbers. ");
scan.nextLine();
}
num2 = scan.nextDouble();
switch (operator)
{
case '+': output = num1 + num2; break;
case '-': output = num1 - num2; break;
case '*': output = num1 * num2; break;
case '/': output = num1 / num2; break;
}
System.out.println("" + num1 + " " + operator + " " + num2 + " = " + output);
}
}

How can i make this code simpler? Also how can i check if input is an int?

Hi im a beginner in Java. How could i make this bais calculator simpler?
Also, i want the user to get an error if num1 or num2 arent Integers. How could i do that?
I already tried parseint and scanner.hasnextint but couldnt get them to work.
import java.util.Scanner;
public class topfirst{
public static void main(String[] args) {
int num1;
int num2;
int result;
String yesorno;
String yes = "yes";
String op;
while(yesorno.equals(yes)){
System.out.println("Please enter the first number :");
Scanner inputnum1 = new Scanner(System.in);
num1 = inputnum1.nextInt();
System.out.println("Please enter the second number :");
Scanner inputnum2 = new Scanner(System.in);
num2 = inputnum2.nextInt();
System.out.println("Please enter an operation :");
Scanner inputop = new Scanner(System.in);
op = inputop.next();
String minus = "-";
String plus = "+";
String multipl = "*";
String div = "/";
while ((!op.equals(minus)) && (!op.equals(plus)) && (!op.equals(multipl)) && (!op.equals(div)))
{
System.out.println("Incorrent operation, try again.");
op = inputop.next();
}
switch(op){
case "+":
result = num1 + num2;
System.out.println(num1 + " + " + num2 + " = " + result);
break;
case "-":
result = num1 - num2;
System.out.println(num1 + " - " + num2 + " = " + result);
break;
case "*":
result = num1 * num2;
System.out.println(num1 + " * " + num2 + " = " + result);
break;
case "/":
result = num1 / num2;
System.out.println(num1 + " / " + num2 + " = " + result);
break;
}
System.out.println("Do you want to calculate something else?");
Scanner inyesorno = new Scanner(System.in);
yesorno = inyesorno.next();
}}
}
import java.util.Scanner;
public class TopFirst {
private static final String PLUS = "+";
private static final String MINUS = "-";
private static final String MULTIPLY = "*";
private static final String DIV = "/";
private static final Scanner INPUT = new Scanner(System.in);
public static void main(String[] args) {
do {
System.out.print("Please enter the first number: ");
int num1 = readInt();
System.out.print("Please enter the second number: ");
int num2 = readInt();
System.out.print("Please enter an operator: ");
String operator = readOperator();
int result = countResult(num1, num2, operator);
System.out.printf("%d %s %d = %d%n", num1, operator, num2, result);
System.out.println("Do you want to calculate something else?");
} while (INPUT.next().equals("yes"));
}
private static String readOperator() {
String operator = INPUT.next();
if (isCorrect(operator)) {
return operator;
} else {
System.out.print("Incorrect operator, try again: ");
return readOperator();
}
}
private static int readInt() {
try {
return Integer.parseInt(INPUT.next());
} catch (NumberFormatException e) {
System.out.print("Incorrect number, try again: ");
return readInt();
}
}
private static boolean isCorrect(String operator) {
return MINUS.equals(operator)
|| PLUS.equals(operator)
|| MULTIPLY.equals(operator)
|| DIV.equals(operator);
}
private static int countResult(int num1,
int num2,
String operator) {
switch (operator) {
case PLUS:
return num1 + num2;
case MINUS:
return num1 - num2;
case MULTIPLY:
return num1 * num2;
case DIV:
return num1 / num2;
default:
return 0;
}
}
}
One Error that needs fixing before anything else:
String yesorno;
String yes = "yes";
String op;
while(yesorno.equals(yes)){
[...]
}
Your String yesorno does NOT equal "yes", so the while-loop is never executed in the first place!

Java scanner requiring multiple inputs

I'd like to ask a question about my code.
I apologize for the inefficiency and the messiness of it, I am still trying to learn java.
System.out.println("Please choose the number corresponding to the operation: ");
System.out.println("1 for add,2 for subtract,3 for multiply, 4 for divide, 5 for print, and 6 for exit: ");
if (sc.nextInt() == 5) {
System.out.println("Your first fraction is: " + num1 + "/" + denom1 + " or in decimal: " + ((float) num1 / denom1));
System.out.println("Your second fraction is: " + num2 + "/" + denom2 + " or in decimal: " + ((float) num2 / denom2));
} else if (sc.nextInt() == 3) {
System.out.println("Multiply: " + (num1 * num2) + "/" + (denom1 * denom2));
} else if (sc.nextInt() == 4) {
System.out.println("Divide: " + (num1 * denom2) + "/" + (denom1 * num1));
} else if (sc.nextInt() == 1) {
int d = denom1 * denom2;
int n1 = num1 * denom2;
int n2 = num2 * denom1;
System.out.println("Addition: " + (n1 + n2) + "/" + d);
} else if (sc.nextInt() == 2) {
int d = denom1 * denom2;
int n1 = num1 * denom2;
int n2 = num2 * denom1;
System.out.println("Subtract: " + (n1 - n2) + "/" + d);
}
else if (sc.nextInt() == 6 ) {
System.exit(0);
}
}
}
When I run the program, the first if statement gets by fine, as I only have to input the number 5 one time. However as you can see from the second else if statement which is the number 3 requires two inputs, I have to enter it two times before the next line comes up. The third else if statement which is the number 4 requires 3 inputs before the next line shows up, and so on with each successive else if statement. I'm sorry if I am not explaining this properly, Does anyone have any idea why this is happening?
Change your code to:
int input = sc.nextInt();
sc.nextLine();
if (input == 5) {
and all other if (sc.nextInt()...)also.
nextInt will consume your input. So if you come to the second if the input is alredy consumed by the first if .
nextLine is nessesary to consume the <ENTER> after the int value.
Try to use switch statement.
package practice;
import java.util.Scanner;
public class Stack{
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
System.out.println("ENTER THE 2 NUMBERS");
int num1=sc.nextInt();
int num2=sc.nextInt();
System.out.println("ENTER THE CHOICE");
int choice='0';
while(choice!=6)
{
choice=sc.nextInt();
System.out.println(choice);
switch(choice)
{
case 1:
int add=num1+num2;
System.out.println("Addition:"+add);
break;
case 2:
System.out.println("Subtract:");
break;
case 3:
System.out.println("Multiply:");
break;
case 4:
System.out.println("Divide:");
break;
case 5:
System.out.println("Your first fraction is:");
System.out.println("Your second fraction is:");
break;
case 6:
System.exit(0);
break;
default:
System.out.println("LOSER");
break;
}
}
sc.close();
}
}

Categories