【问题标题】:Math conditional statement resulting in nothing.数学条件语句不产生任何结果。
【发布时间】:2013-10-10 01:36:10
【问题描述】:

导入 java.util.Scanner;

公开课 MathFun { public static void main(String[] args) {

    Scanner input = new Scanner(System.in);

    int x = 1;

    System.out.println(" Enter a math operation: ");
    String expr = input.next();

    int pos = expr.indexOf("-");

    if ( pos > 0) {
        if (pos == expr.indexOf("+")) {
        int op1 = Integer.parseInt(expr.substring(0, pos));
        int op2 = Integer.parseInt(expr.substring( pos + x , expr.length()));
        System.out.println( op1 + op2);
        } else 
        if (pos == expr.indexOf("-")) {
        int op1 = Integer.parseInt(expr.substring(0, pos));
        int op2 = Integer.parseInt(expr.substring( pos + x , expr.length()));
        System.out.println( op1 - op2);
        } else
        if (pos == expr.indexOf("/")) {
        int op1 = Integer.parseInt(expr.substring(0, pos));
        int op2 = Integer.parseInt(expr.substring( pos + x , expr.length()));
        System.out.println( op1 / op2); 
        } else 
        if (pos == expr.indexOf("%")) {
        int op1 = Integer.parseInt(expr.substring(0, pos));
        int op2 = Integer.parseInt(expr.substring( pos + x , expr.length()));
        System.out.println( op1 % op2);
        } 
        else {
        System.out.println(" Invalid operation ");
            }
        }       
}

} 这可以编译,但我很难初始化 pos = expr.inexOf();。我将如何解决这个问题,以便我的 if 语句开始工作并能够使用字符串?非常感谢您的帮助!

【问题讨论】:

    标签: math conditional statements


    【解决方案1】:

    问题在于 int pos = expr.indexOf("-"); 我确定如果您将输入输入为“25-20”,它会起作用。 你必须先运行一个循环才能找到正确的运算符。

    【讨论】:

      猜你喜欢
      • 2022-12-28
      • 2016-12-05
      • 1970-01-01
      • 2012-09-08
      • 1970-01-01
      • 1970-01-01
      • 2021-09-07
      • 2018-03-30
      • 1970-01-01
      相关资源
      最近更新 更多