我的输出卡在同一件事上

时间:2017-10-05 07:51:02

标签: java switch-statement break

import java.util.Scanner;

public class QuestionThreeB {
  public static void main(String[] args) {
    int number;
    Scanner keyboard = new Scanner(System.in);
    System.out.print("Enter 1, 2, or 3: ");
    number = keyboard.nextInt();
    switch (number) {
      case '1':
        System.out.println("You entered 1.");
        break;
      case '2':
        System.out.println("You entered 2.");
        break;
      case '3':
        System.out.println("You entered 3.");
        break;
      default:
        System.out.println("That's not 1, 2, or 3!");
    }
  }
}

当我编译并运行程序时,我最后输出一行("那不是1,2或3!")作为输出,无论我放什么值in。我试图使用if then语句来修复它,它编译但结果是相同的

3 个答案:

答案 0 :(得分:3)

变量number的类型为int。 Switch语句正在检查字符(数字是单引号'1')。

1与'1'不同。您需要删除单引号以比较整数。

public class QuestionThreeB {
  public static void main(String[] args) {
    int number;
    Scanner keyboard = new Scanner(System.in);
    System.out.print("Enter 1, 2, or 3: ");
    number = keyboard.nextInt();
    switch (number) {
      case 1:
        System.out.println("You entered 1.");
        break;
      case 2:
        System.out.println("You entered 2.");
        break;
      case 3:
        System.out.println("You entered 3.");
        break;
      default:
        System.out.println("That's not 1, 2, or 3!");
    }
  }
}

答案 1 :(得分:0)

在你的代码上,输入需要一个整数而case是char(因为单引号)。只需删除它

.

答案 2 :(得分:0)

在Java中int数据类型与String数据类型完全不同。你在这里向控制台询问一个int:number = keyboard.nextInt();然后将它与switch语句中的字符串进行比较,该字符串永远不会相等。 您有两种选择:1)从交换机中的数字中删除引号(由Berger建议)2)执行keyboard.nextLine()而不是keyboard.nextInt()