java - 向现有的 java 程序添加循环?

标签 java loops while-loop do-while repeat

我需要修改我的程序,以便在需要时可以多次运行它。如果用户输入 Q 或 q,并且输入除请求的条目(或退出命令)以外的任何内容,我需要退出程序,问题将重复。 这是我到目前为止的代码:

import java.util.Scanner;

public class TemperatureLoop
{

    private static Scanner keyboard = new Scanner(System.in);

    public static void main(String[] args) 
    {

        System.out.println("Enter a temperature in degrees (for example 32.6): ");
        double temp;
        temp = keyboard.nextDouble();
        System.out.println("Enter 'F' (or 'f') for Fahrenheit or 'C' (or 'c') for Celsius: ");
        String letter = keyboard.next();
        double total = 0;
        //if Farenheit then do this equation
        if (letter.equals("F") || (letter.equals("f")))
        {
            total = ((temp-32)*5)/9; //convert the entered temperature to Celsius
            System.out.println(temp + " degrees F = " + total + " degrees Celsius");
        }
        else //if Celsius then do this
        if (letter.equals("C") || (letter.equals("c")) )
        {
            total = (((temp*9))/5)+32; //convert the entered temperature to Farenheit
            System.out.println(temp + " degrees C = " + total + " degrees Fahrenheit");
        }
    }
}

最佳答案

我建议将您所拥有的内容放入 while 循环中,如果用户输入“Q”或“q”,该循环就会中断。类似于下面的内容:

// Declare your breaking condition variable outside the while loop
boolean done = false;
while (!done){
   //  Your existing code here
   //  A conditional to check for 'Q' or 'q'
   //  set done to true if the above line evaluates as true.
}

关于java - 向现有的 java 程序添加循环?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42172325/

相关文章:

java - 去除List中重复项的方法

java - jdbc多线程使用教程

java - 将条目从一个 Multimap 复制到另一个

c++ - 如何有效地用另一个 std::string 的迭代值替换 std::string 中的字符?

c - 为什么我的程序不会停止循环?

c - 为什么我总是得到负值?

java - 如何获取参数化类实例

java - ZK onKeyUp 与正则表达式

java - 需要帮助 输入字母时循环此操作

while循环中的PHP第一个和最后一个类