SWITCH语句不起作用 - Java

时间:2014-11-04 14:18:00

标签: java switch-statement

我正在制作一个程序来计算某种材料的声速。这是代码:

  switch (user_Choice)
 {
case 1:
  System.out.println("The sound wave took " + speed.getSpeedInAir() + " seconds to travel through " +
                     distance + " feet of Air.");
  break;

case 2:
  System.out.println("The sound wave took " + speed.getSpeedInWater() + " seconds to travel through " +
                     distance + " feet of Water.");
  break;

case 3:
  System.out.println("The sound wave took " + speed.getSpeedInSteel() + " seconds to travel through " +
                     distance + " feet of Steel.");
  break;

default:
  System.out.println("Not a valid input.");}

我不知道为什么这不起作用。我可以没有那么多" +"每个案例的迹象?

编辑:这是user_Choice输入

System.out.println("Pick a medium (1, 2, or 3):\n1. Air\n2. Water\n3. Steel");
user_Choice = kbReader.nextInt();
System.out.print("Enter the distance the sound wave traveled in feet: ");
distance = kbReader.nextDouble();
SpeedOfSound speed = new SpeedOfSound(distance);

1 个答案:

答案 0 :(得分:0)

如果kbReaderScanner,请记住nextInt()nextDouble()需要nextLine() in order to get rid of the \n。在nextDouble()之后致电nextInt()会向distance提供值null

解决方法是在第一个nextLine()之后添加nextInt()

System.out.println("Pick a medium (1, 2, or 3):\n1. Air\n2. Water\n3. Steel");
user_Choice = kbReader.nextInt();
kbReader.nextLine(); //Consumes the \n (new line) character.
System.out.print("Enter the distance the sound wave traveled in feet: ");
distance = kbReader.nextDouble();
SpeedOfSound speed = new SpeedOfSound(distance);

如果在user_Choice = kbReader.nextInt();之前您正在执行另一个nextInt()或类似内容,switch将始终选择默认值,因为user_Choicenull。< / p>