扫描仪& if-then-else问题

时间:2017-03-13 06:32:54

标签: variables initialization java.util.scanner

我正在尝试根据用户输入创建结果(result1)。我得到一个错误,说可能没有启动result1。如果我通过输入int result1 = 0;将其添加到上面的代码中,我的if-then-else语句会导致system.out.println(result1);每次都给出0的结果。它完全跳过我的if-then-else语句。一旦用户输入字符串,是否应该立即启动result1?我感谢任何建议或见解。

import java.util.Scanner;

public class Main {

    public static void main(String[] args) {


        Scanner sc0 = new Scanner(System.in);
        System.out.print("What would you like to do?: (A)Addition (B)Subtraction (C)Multiplication (D)Division: ");
        String input0 = sc0.nextLine();

        Scanner sc1 = new Scanner(System.in);
        System.out.print("Enter a number: ");
        String input1 = sc1.nextLine();

        Scanner sc2 = new Scanner(System.in);
        System.out.print("Enter a number: ");
        String input2 = sc2.nextLine();

        int int1 = Integer.parseInt(input1);
        int int2 = Integer.parseInt(input2);


        if (input0 == "A")
        {
            result1 = int1 + int2;
        }
        else if (input0 == "B")
        {
            result1 = int1 - int2;
        }
        else if (input0 == "C")
        {
            result1 = int1 * int2;
        }
        else if (input0 == "D")
        {
            result1 = int1 / int2;
        }
        else {
            System.out.println("You have entered an invalid option.");
            System.exit(0);
        }


        System.out.println("Your result is, " + result1 + "!");



    }
}

1 个答案:

答案 0 :(得分:0)

比较字符串时使用equals而不是==运算符。

int result1 = 0;
        Scanner sc0 = new Scanner(System.in);
        System.out.print("What would you like to do?: (A)Addition (B)Subtraction (C)Multiplication (D)Division: ");
        String input0 = sc0.nextLine();

        Scanner sc1 = new Scanner(System.in);
        System.out.print("Enter a number: ");
        String input1 = sc1.nextLine();

        Scanner sc2 = new Scanner(System.in);
        System.out.print("Enter a number: ");
        String input2 = sc2.nextLine();

        int int1 = Integer.parseInt(input1);
        int int2 = Integer.parseInt(input2);


        if (input0.equals("A"))
        {
            result1 = int1 + int2;
        }
        else if (input0.equals("B"))
        {
            result1 = int1 - int2;
        }
        else if (input0.equals("C"))
        {
            result1 = int1 * int2;
        }
        else if (input0.equals("D"))
        {
            result1 = int1 / int2;
        }
        else {
            System.out.println("You have entered an invalid option.");
            System.exit(0);
        }


        System.out.println("Your result is, " + result1 + "!");

它总是返回0,因为你使用的是==运算符,它不会影响你的任何一个IF条件。