2016-11-12 57 views
1

当我为current5输入20时,minuteCurrent应该是240,但即使minuteCurrent超过240,部分也会继续工作。为什么?我尝试了更多的东西,但他们没有帮助。这是为什么 - 而计算是错误的?

import java.util.Scanner; 

class Person { 

String name; 
int heartRatePer5; 
int current5; 

void alarm() { 

    for (int i = 0; i < 3; i++) 
     System.out.print("!!! "); 
    System.out.println(); 
} 

void stopAlarm() { 
    System.out.println("Alarm stopped"); 
    } 
} 

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

    Person person1 = new Person(); 

    Scanner input = new Scanner(System.in); 

    System.out.println("Enter the current heart rate per 5 seconds: "); 
    person1.current5 = input.nextInt(); 
    int minuteCurrent = person1.current5 * 12; 
    // minuteCurrent = 0; 

    do { 
     System.out.println("Normalizing."); 
     person1.stopAlarm(); 
     //minuteCurrent = input.nextInt(); 
     break; 
    } 

    while (minuteCurrent < 220); 

} 

}

+0

http://ericlippert.com/2014/03/05/how-to-debug-small-programs/ – Biffen

+2

你的'do-while'将在第一次运行时总是停止,因为你最后有'break' 。你的意思是在它之前有一个if语句吗? –

+1

请将您的代码修改为https://stackoverflow.com/help/mcve。整个“警报”是不需要的。 – Robert

回答

0

do部分继续工作,即使minuteCurrent超过240

当你说保持工作:我假设你的意思是:工作正好一次

这是正常的;这是do的保证。 The statements within the do block are always executed at least once

也许你想要一个正常的while循环呢?

电感情况下应该是这样的:

while (minuteCurrent < 220) { 
    minuteCurrent = input.nextInt(); 
} 

我不清楚效果的person1.stopAlarm();什么,或者你想多少次打印的“正常化”的消息。所以这可能不是您的算法的完整解决方案。但我认为从do-while切换到常规while循环应该至少可以解决您所描述的混淆问题。

1

do-while循环比while循环的工作方式不同。

注意while循环条件现在被移动到do之后,而 循环体。 do while循环体总是至少执行一次, 然后重复执行while while循环条件为 为true。

See more here.

你怎么能解决这个问题?改变你的while循环,看起来像这样:

while (minuteCurrent < 220) { 
      System.out.println("Normalizing."); 
      person1.stopAlarm(); 
      break; 
} 

此外,我不知道为什么你使用while循环。只使用if语句会更有意义 - 与while循环相同,最后会有中断。

+1

我希望它不断问它是否不少于220.我应该可以用if语句来做,是的。谢谢 –