SWITCH语句不工作 - Java
问题描述:
我正在制作一个程序来计算通过某种材料的声音的速度。这里是代码:SWITCH语句不工作 - Java
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);
答
如果kbReader
是Scanner
记得nextInt()
和nextDouble()
需要nextLine()
in order to get rid of the \n
。在nextInt()
之后调用nextDouble()
将给出distance
值null
。
一种解决方法是第一个nextInt()
后添加nextLine()
:
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
。
+0
@Dalton克雷格请确保您所编辑的内容是有效的,并且您还输入了有效的编辑摘要 – 2014-11-04 18:44:40
什么是错误? – AlfredoVR 2014-11-04 14:19:44
指定“不工作”是什么意思?它应该如何工作? – Eypros 2014-11-04 14:19:44
它总是显示默认选项?你如何阅读user_Choice var? – AndreDuarte 2014-11-04 14:20:17