带有while和if语句的

时间:2016-10-15 00:51:12

标签: java

您好我是Java新手,对于我的介绍类,我必须编写一些执行以下操作的内容:定义用户输入,用户输出,While语句和一些数学计算的问题。

我想要做的是让用户提示脚和英寸的高度,如果它超过5&8; 8他们无法进入过山车;如果它是5&8;或更少,他们可以。我意识到这将更容易,就像一个if else的东西,但我需要使用while;我们还没有覆盖,但我也无法使用它。我可能搞砸了,并且有更好的方法可以做到这一点,但这是我到目前为止所做的。

import java.util.Scanner;

public class coasterHeight
{
   public static void main(String[] args)
   {


Scanner keyboard = new Scanner(System.in);
int feet;
int inches;

System.out.println ("Your must be at least 5'8 to ride this ride.");
System.out.println ("Please enter your height in feet:");

 feet = keyboard.nextInt();
 System.out.println ("Please enter your height in inches:");

 inches = keyboard.nextInt ();



 while (feet <= 5 && inches <= 8)
 {
 System.out.println("You can go on this ride.");
break;
}


 {
 if (feet >= 6 && inches >=9)

 {
 System.out.println ("You cannot go on this ride.");
 }
}
  }


 }

所以这就是问题所在。当输入符合while要求时它工作正常(它曾经用#34进行无限循环;你可以继续这个骑行&#34;但我发现了break;),但对于if语句,没有出现在输出。 &#34;你不能继续这个骑行&#34;,什么也没有出现,没有任何错误或任何它只是在我输入超过5&#8; 8的高度后结束输出。就像我说的那样可能很糟糕但是感谢任何帮助,谢谢。

3 个答案:

答案 0 :(得分:1)

您的程序无法正常工作的原因是因为您的逻辑不正确。

仔细查看您的情况,并考虑用户可以进入的不同可能性。

feet <= 5 && inches <= 8

和操作&&意味着这两个部分必须同时为真才能使语句评估为真。因此,身高5英尺9英寸的人会导致这种情况评估为假。

feet >= 6 && inches >=9出现同样的问题,因为7英尺1英寸高的人会导致这种情况评估为假。

此外,您的情况似乎已经逆转。在程序的顶部,你说有人必须至少5英尺8英寸才能继续骑行但是你检查的时间少于那个并让它们继续下去。

答案 1 :(得分:0)

要以伪代码回答这个问题(您可以使用您已经拥有的内容填写详细信息):

while not valid input (not a number, is negative, etc.)
    get height from user

if height allowed on ride
    say "ok"
else
    say "no dice"

另请注意:请注意feet <= 5 && inches <= 8true(例如)feet = 7inches = 1。我觉得他们应该被允许骑车。

答案 2 :(得分:0)

尝试使用floatdouble代替float height = 0.00double height = 0.0。 然后,您可以在while语句中使用它,例如

    while (height >= 5.8){
        System.out.println("You cannot enter the ride");
        break;
    }
    while (height < 5.8){
        System.out.println("You can enter the ride");
        break;
    }