问题
i want to input a int to get first number then use a string to get the operator and another int for the second number. user should input some thing like 10+20. but as soon as i enter the "+" then i get an error why?
cuz it works if i manually add the values into the sum.calc(); myself like sum.calc(12, "+", 24); then it works ill get 36
PART 1:
import java.util.Scanner;
public static void main(String[] args) {
math sum = new math();
Scanner input = new Scanner(System.in);
double a = input.nextDouble();
String b = input.nextLine();
double c = input.nextDouble();
sum.calc(a, b, c);
input.close();
}
PART 2:
public class math {
public void calc(double a, String b, double c){
double t;
switch(b){
case "+":
t = a + c;
System.out.println(a+" + "+c+" = "+t);
break;
case "-":
t = a - c;
System.out.println(a+" - "+c+" = "+t);
break;
case "*":
t = a * c;
System.out.println(a+" * "+c+" = "+t);
break;
case "/":
t = a / c;
System.out.println(a+" / "+c+" = "+t);
break;
}
}
}
回答1:
Try using input.next();
instead of input.nextLine();
Because input.nextLine();
advances this scanner past the current line and returns the input that was skipped. so if your input was 20, +, and 24, your method calc
would get 20,24,null.
回答2:
input.next() works instead of input.nextLine() for strings.Try it out
来源:https://stackoverflow.com/questions/42760429/i-cant-get-my-calculator-to-work