用户使用Java返回温度转换

时间:2017-04-19 08:15:25

标签: java

我想创建一个程序,将温度从华氏温度转换为摄氏温度,并让用户可以选择继续提供温度,直到他们选择不这样做。这是我的代码。

import java.util.Scanner;

public class TempConversions 
{
private static int temperature;
private static int fahrenheit;


public TempConversions () 
{
fahrenheit = 0;
temperature = 0;

}

public static void main(String[] args) 
{
    MayenHeading.getHeading("Assignment 4 ");

    System.out.printf("  Temperature Converter\n");
    Scanner sc = new Scanner(System.in);

    System.out.printf("\n  Enter temperature to convert -->   ");
    temperature = sc.nextInt();



    fahrenheit = ((temperature - 32)*5)/9;
    System.out.printf("  The temperature is " + fahrenheit + " degrees                           fahrenheit");

    // see if the user wants to continue
        System.out.print("\n  Continue? (y/n): ");
        String choice = sc.next();

    {   
    System.out.printf("\n  Program completed.");
    MayenDate.printfDate();
    MayenDate.printfTime();
    }

}
}

2 个答案:

答案 0 :(得分:0)

你可以使用do while循环

public class TempConversions 
        {
        private static int temperature;
        private static int fahrenheit;


        public TempConversions () 
        {
        fahrenheit = 0;
        temperature = 0;

        }

        public static void main(String[] args) 
        {
            MayenHeading.getHeading("Assignment 4 ");

    do{


            System.out.printf("  Temperature Converter\n");
            Scanner sc = new Scanner(System.in);

            System.out.printf("\n  Enter temperature to convert -->   ");
            temperature = sc.nextInt();



            fahrenheit = ((temperature - 32)*5)/9;
            System.out.printf("  The temperature is " + fahrenheit + " degrees                           fahrenheit");

            // see if the user wants to continue
                System.out.print("\n  Continue? (y/n): ");
                String choice = sc.next();
        }while(choice.chatAt(0) == 'y');
            {   
            System.out.printf("\n  Program completed.");
            MayenDate.printfDate();
            MayenDate.printfTime();
            }

        }
        }

答案 1 :(得分:0)

所以我这样做的方法是将一个常量指定为退出变量,例如

Final int EXIT = 1;

这使您可以在将来进行快速更改,假设您有很多选项并且需要使用1,您只需将其中一个简单地更改为其他任何内容,而不是在程序中多次查找1。 所以我将在下面为您编写一些框架,以便让您的代码完成您想要的任务。

Public static void main(String []args)
{

     Public final int EXIT = 1;

      //Declare your other variables
      //Declare any other classes your using
       //Start of a do while loop
       Do
        {

             // Your conversion program goes here
              //Prompt user for exit


         }
         while(choice != EXIT)

   }//End of main

我在while循环或for循环中执行while循环的逻辑是你需要至少执行一次。 如果你没有,或者你知道用户想要循环多少次,你将使用另一种循环。