添加循环到现有的Java程序?

时间:2017-02-11 04:43:10

标签: 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");
        }
    }
}

2 个答案:

答案 0 :(得分:1)

如果用户输入“问题”,我建议将你所拥有的内容放入while循环中。或者' 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.
}

答案 1 :(得分:0)

在这种情况下,你应该使用do-while循环

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

循环如何工作,do部分中的任何内容始终至少执行一次。然后它将检查while条件以确定是否再次执行do部分。如您所说,一旦用户输入Qq,程序将结束,因为while条件将评估为false并且do部分将不再执行。因此,在这种情况下循环将终止。

当您输入Qq时会发生什么? do部分在技术上会发生,但是你的if语句将被忽略,因为它不满足这些条件。达到while检查后,条件将评估为false,从而导致循环结束。如果您输入了类似Mg的内容,那么if语句将被忽略,但循环不会结束,因为while条件不会计算为false,因此程序将再问一次温度和度数。