【问题标题】:Java choose whether to add or subractJava选择是加还是减
【发布时间】:2013-10-20 20:02:42
【问题描述】:

我的问题很简单,为什么如果我选择 + m 则不加,如果我选择 - 则减去 -

感谢所有帮助。在此先感谢,我在这里做错了什么,我知道我在正确的轨道上

public static void main(String[] args) throws Exception {

    int tal1, tal2;
    char operator;

    Scanner input1 = new Scanner(System.in);
    Scanner input2 = new Scanner(System.in);
    Scanner input3 = new Scanner(System.in);

    System.out.println("Write in a 1st integer");
    tal1 = input1.nextInt();

    System.out.println("Write in 2nd intger");
    tal2 = input2.nextInt();

    System.out.println("Do you want to add or subtract please choose + or -");
    operator = (char) input3.nextInt();

    if (operator == '-') {
        System.out.println("Tal1 - Tal2 = " + (tal1 - tal2));
    } else if (operator == '+') {
        System.out.println("Tal1 + Tal2 = " + (tal1 + tal2));
    }

    System.out.println("Wrong thing to do buddy");

}

【问题讨论】:

  • 为什么有这么多扫描仪?一个就够了。 -+ 也不是 int 所以你不能使用 nextInt 来得到这个。考虑使用next 并将结果存储在字符串中。还要记住将字符串与equals 而非== 进行比较。

标签: java add subtraction


【解决方案1】:

使用next() 代替nextInt() 并使用String 代替char 并将字符串与str_1.equals("+") 进行比较,如果字符串匹配则返回true

【讨论】:

    【解决方案2】:

    好朋友:

    你有两个错误:

    1- 在 public static void main 之前你还没有开始上课。

    2- 你在这一行有一个错误。

    operator = (char)input3.nextInt();
    

    '+' 和 '-' 不是 int。所以你不能为他们得到一个 int。

    请改用我为您编写的以下代码:

    class Test2
    {
    public static void main(String[] args) 
    {
    
    
    int tal1, tal2;
    char operator;
    
    Scanner input1 = new Scanner(System.in);
    Scanner input2 = new Scanner (System.in);
    Scanner input3 = new Scanner (System.in);
    
        System.out.println("Write in a 1st integer");
        tal1=input1.nextInt();
    
        System.out.println("Write in 2nd intger");
        tal2=input2.nextInt();
    
    
    
    
        System.out.println("Do you want to add or subtract please choose + or -");
        operator = input3.nextLine().charAt(0);
    
    
    
    
        if (operator == '-')
        {
            System.out.println("Tal1 - Tal2 = "+(tal1-tal2)); 
        }
    
        else if (operator == '+')
        {
    
                System.out.println("Tal1 + Tal2 = "+(tal1+tal2)); 
        }
    
            System.out.println("Wrong thing to do buddy");
    }
    
    
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-08-25
      • 2010-11-02
      • 2010-11-08
      • 2011-03-03
      • 1970-01-01
      • 2012-09-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多