i cant get my calculator to work

妖精的绣舞 提交于 2019-12-13 22:50:16

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!