Reputation: 29
So I'm a noob coder (new to the website), trying to teach myself and I'm currently making a simple calculator. Atm, I've added pi to it with an if statement that checks the input. However, when I type a double it doesn't do anything and I'm not sure why.
package testing;
import java.util.Scanner;
public class Calculator {
@SuppressWarnings("resource")
public static void main(String[] args) {
String piCheck = "pi";
Double n1 = null;
Scanner reader = new Scanner(System.in);
System.out.println("Welcome to Calculator!");
System.out.println(" ");
System.out.println("Enter a number, ");
System.out.println("or enter 'pi' to insert PI,");
if (reader.nextLine().toLowerCase().contains(piCheck)) {
n1 = Math.PI;
} else {
n1 = reader.nextDouble();
}
Scanner reader2 = new Scanner(System.in);
System.out.println("Would you like to multiply, divide, add, subtract?");
String uOperation = reader2.nextLine();
int operation = 1;
switch (uOperation.toLowerCase()) {
case "multiply":
operation = 1;
break;
case "multiplication":
operation = 1;
break;
case "times":
operation = 1;
break;
case "divide":
operation = 2;
break;
case "division":
operation = 2;
break;
case "add":
operation = 3;
break;
case "addition":
operation = 3;
break;
case "subtract":
operation = 4;
break;
case "subtraction":
operation = 4;
break;
default:
System.out.println("Invalid operation! Rerun Calculator!");
break;
}
if (operation == 1) {
System.out.println("What do you want to multiply " + n1 + " by?");
} else if (operation == 2) {
System.out.println("What do you want to divide " + n1 + " by?");
} else if (operation == 3) {
System.out.println("What do you want to add to " + n1 + "?");
} else if (operation == 4) {
System.out.println("What do you want to subtract from " + n1 + "?");
} else {
System.out.println("Something went wrong!");
}
double n2 = reader.nextDouble();
System.out.println("Here's your result!");
double resultM = n1*n2;
double resultD = n1/n2;
double resultA = n1+n2;
double resultS = n1-n2;
if (operation == 1) {
System.out.println(n1 + " multiplied by " + n2 + " equals:");
System.out.println(resultM);
} else if (operation == 2) {
System.out.println(n1 + " divided by " + n2 + " equals:");
System.out.println(resultD);
} else if (operation == 3) {
System.out.println(n1 + " plus " + n2 + " equals:");
System.out.println(resultA);
} else if (operation == 4) {
System.out.println(n1 + " take away " + n2 + " equals:");
System.out.println(resultS);
} else {
System.out.println("Something went wrong!");
}
}
}
Upvotes: 0
Views: 54
Reputation: 393851
Your problem is that you are reading the input in the condition, so if you enter a double, the else clause expects more input to be entered, since the first input was already consumed by reader.nextLine()
.
You have to save the input and reuse it :
String input = reader.nextLine();
if (input.toLowerCase().contains(piCheck)) {
n1 = Math.PI;
} else {
n1 = Double.parseDouble(input);
}
Upvotes: 4