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);
答案 0 :(得分:0)
如果kbReader
是Scanner
,请记住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_Choice
为null
。< / p>