繁体   English   中英

在现有的Java程序中添加循环?

[英]Adding loops to an existing java program?

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

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.
}

在这种情况下,您应该使用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 part。 就像您说的那样,一旦用户输入Qq ,该程序将结束,因为while条件将评估为false,并且do部分将不再执行。 因此,在这种情况下,循环将终止。

输入Qq时会发生什么? 从技术上讲, do部分将发生,但是您的if语句将不被满足,因为它不满足那些条件。 一旦达到while检查,条件将评估为false,从而导致循环结束。 如果您输入Mg ,则if语句将被忽略,但循环不会结束,因为while条件不会求值为false,因此程序将再次询问您温度和度数。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM