Not getting the expected output from the do-while loop - java

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

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!

validating char user input loop

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

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!

Validation error in code

I am experiencing trouble in the creation of my reverse polish notation calculator with my validation code. I need the calculator to accept the two shift operators (<< and >>) as part of the calculations. The following snippets of code is the validation part and also the calculation.
public static boolean isInt(String userinput) {
try {
Integer.parseInt(userinput); // Try to parse. Makes sure that the values entered are actual numbers
return true; // Boolean value to show if the equation entered is valid or not
} catch (NumberFormatException e) {
System.out.println("Please enter a valid expression!");
invalidlines++;
return false;
}
}
public static boolean isValidLine(String line) {
line = line.trim();
if (line.length() <= 4) { // Trims the lines down to 4 and ensures there is no spaces being included
return false;
} else {
String[] calcarray = new String[3];
calcarray = line.split(" ");
String operators = new String("[+\\-\\*\\/\\<<\\>>\\%\\&\\|]"); // Validator using regular expressions to check the operator used
if (isInt(calcarray[0].toString()) && isInt(calcarray[1].toString()) && calcarray[2].matches(operators)) { // Checks that the operator in the string matches the ones in the regular expression
return true;
} else {
return false;
}
}
}
below is the calculator part:
String keyboardInput = new String();
Scanner kbScan = new Scanner(System.in);
int answer = 0;
while (true) {
display("Please enter an equation");
keyboardInput = kbScan.nextLine();
if (isValidLine(keyboardInput)) {
String[] equation = new String[3]; // We know that this is only going to contain 3 to be valid
equation = keyboardInput.split(" "); // split this up, as it's stored with the spaces.
int num1 = Integer.parseInt(equation[0]);
int num2 = Integer.parseInt(equation[1]);
switch (equation[2]) { // This case switch checks the third position of the
// string to decide which operator is being used. It then works out the
// answer and breaks to the next instruction
case ("+"):
answer = num1 + num2;
break;
case ("-"):
answer = num1 - num2;
break;
case ("/"):
answer = num1 / num2;
break;
case ("*"):
answer = num1 * num2;
break;
case ("<<"):
answer = num1 << num2;
break;
case (">>"):
answer = num1 >> num2;
break;
case ("%"):
answer = num1 % num2;
break;
case ("|"):
answer = num1 | num2;
break;
case ("&"):
answer = num1 & num2;
break;
}
display("Your post fix expression: " + equation[0] + " " + equation[1] + " " + equation[2]);
display("Your calculation: " + equation[0] + " " + equation[2] + " " + equation[1] + " = " + answer);
} else {
display("The equation you entered is invalid");
}
}
Whenever a valid expression is entered the following error is shown in the console:
Enter F for file calculator or K for keyboard input
k
Please enter an equation
10 2 <<
The equation you entered is invalid
Please enter an equation
And I cannot figure out which part of my validation is wrong for these expressions.
Problem is with your operators regex.
User rather something like:
("\\+|\\-|\\*|\\/|<<|>>|\\%|\\&|\\|")

Categories