简单计算器无法超越println

用户3447081

所以这是我的代码。

https://ideone.com/ok42QZ

    System.out.println("setcaculatorinput");
    Scanner sc = new Scanner(System.in);
    int z = sc.nextInt();
    System.out.println("setvalueA");
    int a = sc.nextInt();
    System.out.println("setvalueB");

主要问题是我无法通过System.out.println(“ setcaculatorinput”),因为它在该行之后立即崩溃。

尼康

让我格式化您的代码...首先:

if ("+".equals(z))
    ; // it's an empty condition!

{ // this is an init block
 System.out.println(c);
}

您所有的代码都是“格式化的”:

public static void main(String[] args) throws java.lang.Exception {
        System.out.println("setcaculatorinput");
        Scanner sc = new Scanner(System.in);
        int z = sc.nextInt();
        System.out.println("setvalueA");
        int a = sc.nextInt();
        System.out.println("setvalueB");
        int b = sc.nextInt();
        int c, d, e, f;

        c = (a + b);
        d = (a - b);
        e = (a * b);
        f = (a / b);

        if ("+".equals(z))
            ;
        if ("-".equals(z))
            ;
        if ("*".equals(z))
            ;
        if ("/".equals(z))
            ;

        { // init block
            System.out.println(c);
            System.out.println(d);
            System.out.println(e);
            System.out.println(f);
        }
        System.exit(0);
    }

显示该错误的原因是,您尝试读取一个非整数字符,读取了Javadoc的Javadoc,new Scanner("").nextInt();然后您将看到该错误:“ InputMismatchException-如果下一个标记与Integer正则表达式不匹配,或者超出范围”。

我为您提供了一个简短的解决方案,但由于不对输入内容执行任何检查,因此不建议这样做。

public static void main(String[] args) {
        System.out.println("setcaculatorinput");
        Scanner sc = new Scanner(System.in);
        int result = 0;

        System.out.println("setvalueA=");
        int a = sc.nextInt();

        System.out.println("setOperator=");
        String op = sc.next();

        System.out.println("setvalueB=");
        int b = sc.nextInt();

        if ("+".equals(op))
            result = a + b;
        else if ("-".equals(op))
            result = a - b;
        else if ("*".equals(op))
            result = a * b;
        else if ("/".equals(op))
            result = a / b;

        System.out.println("The result is=" + result);
        System.exit(0);
    }

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章