2017-02-22 184 views
-1

我正在处理一些代码,它接受用户输入,并在输入不是程序所要查找的内容时使用while语句循环。
由于某些原因,即使条件未满足,while语句也始终执行。
我试过修复条件,但我不知道发生了什么事。虽然循环跳过条件

do { 
    System.out.println("Enter a height within 0 and 23"); 
    height = s.nextInt(); 
} while (height < 0 || height > 23);{ 
    System.out.println("Please enter an integer within 0 and 23"); 
    height = s.nextInt(); 
} 

任何帮助,非常感谢!

+2

如果分号除去该代码将是无效 - 'while'和前面的'do'循环一起,而不是跟在下面的块。 –

+0

要添加到以前的评论,第二组花括号与此代码段无关。 – SteveFerg

回答

0

我认为一个标准while循环会适合你更好

int height = 0; 
while (True) { 
    System.out.println("Enter a height within 0 and 23"); 
    height = s.nextInt(); 
    if (height < 0 || height > 23) { 
     System.out.println("Please enter an integer within 0 and 23"); 
     continue; 
    } else break; 
} 

基本上,这个“码块”没有应用到一个做而

{ 
    System.out.println("Please enter an integer within 0 and 23"); 
    height = s.nextInt(); 
} 
+0

啊,这可以帮助我与这个谢谢 –

+0

很高兴听到它。你可以通过[接受答案]来显示你的感谢(// stackoverflow.com/help/someone-answers)。 –

1

你有while语句代码太多。所有你需要的是:

do { 
    System.out.println("Enter a height within 0 and 23"); 
    height = s.nextInt(); 
} while (height < 0 || height > 23); 

一个do ... while循环有while底,而不是开始。

+0

我想你错过了“请输入”提示 –

+0

这个答案是正确的,但也许可以添加更多解释为什么。 do while循环执行第一个{}对之间的代码至少一次,如果条件为真(在代码块执行后评估),则执行更多次。因此,时间之后的第二个代码块就在它自己的代码块中,与任何循环无关,因此是不必要的。 – Encaitar

0

你有一个do循环和一个while循环混合在一起。摆脱“do {”和第一个“}”。也请做什么shmosel说,并删除“;”。这将允许您在while循环外获得第一个int,然后如果它在您的条件之内,它将开始循环。

System.out.println("Enter a height within 0 and 23"); 
    height = s.nextInt(); 
    // now have 1st condition for the whie loop 
    while (height < 0 || height > 23) { 
    System.out.println("Please enter an integer within 0 and 23"); 
    height = s.nextInt(); 
    } 
0

正如问题中所述,while语句总是在即使条件不满足时执行。但这不是事实。

while循环是没有得到执行用于输入时的高度在0和23(含) 输入之间:0 < =高度< = 23