【问题标题】:Errors involving the location of variables涉及变量位置的错误
【发布时间】:2013-10-09 23:03:18
【问题描述】:
import java.util.Scanner;

public class MathFun {
    public static void main(String[] args) {

        Scanner input = new Scanner(System.in);

        int x = 0;

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

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

        if ( pos >= 0) {
            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 ");
                }
            }       
    }

虽然这是通过javac,但程序会自动说

an ex out of range: -1
at java.lang.String.substring(String.java:1937)
at MathFun.main(MathFun.java:21)

循环有问题吗? 我只想做一个简单的循环,让用户输入一个字符串 2+2 并让循环将其作为字符串读出并打印结果。谢谢!

【问题讨论】:

  • Is there something wrong with the loop? 循环在哪里

标签: string variables loops math


【解决方案1】:

您的代码中有很多问题。

  1. string expr = in.next(); 应该是 String expr = in.next();
  2. 您在声明之前使用了pos 变量。严重错误。
  3. int pos = expr.indexOf(); //什么索引??
  4. 您的扫描仪名称是 input 而不是 in

这些只是编译时错误。修复它们,然后查看您的程序的行为方式

【讨论】:

  • 程序编译运行,但我输入字符串时打印错误
猜你喜欢
  • 2019-05-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-05-05
  • 2012-02-19
  • 2011-12-21
  • 1970-01-01
相关资源
最近更新 更多