如何不在循环中打印所有内容,而是根据决策进行打印

问题描述 投票:0回答:1

所以我有一个问题要问 Java。我想一次而不是每次都打印方法中的所有内容。 该方法称为

refrigeratorInformation
。 所以我的问题是,我如何只运行一次该方法,然后再次询问我下一步想做什么。这是代码:

System.out.println("State what you would like to do with the refrigerator:");
USER_INPUT = input.nextLine();
while(true){
     if (USER_INPUT.equalsIgnoreCase("I want to close the refrigerator")){
         TimeUnit.SECONDS.sleep(1);
         System.out.println("Shutting down!");
         TimeUnit.SECONDS.sleep(3);
         System.exit(0);
     } else if (USER_INPUT.equalsIgnoreCase("What is the current temperature inside the refrigerator")){
         refrigeratorTemperature();
     } else if (USER_INPUT.equalsIgnoreCase("Show me some info about the refrigerator")){
         refrigeratorInformation();
     }            
}

这里是方法代码:

public void refrigeratorInformation(){
    dimension= "Width is 178cm, Height 66,8cm & length is 59,5cm";
    usage = 157;
    volume = 707.5; // in liter
    name = "Build Your Body Fat";
    weight = 63;
    try{
        System.out.println(name);
        System.out.println(weight);
        System.out.println(volume +" Liter");
        System.out.println("The refrigerator has a usage of " + usage + "kWh");
        System.out.println(dimension);
        TimeUnit.SECONDS.sleep(5);
    } 
...

如果你能帮助我,我将不胜感激

java loops while-loop break
1个回答
2
投票

如果你想停止执行你把

return
语句放在这个方法的末尾的方法,如果你想跳过一个迭代你把
continue
放在你的循环中跳过一个迭代。如果你放
break
你的循环停止而不是方法。 我相信你正在寻找
break

阅读文档while循环

© www.soinside.com 2019 - 2024. All rights reserved.