使用Java进行温度转换的用户返回
我想创建一个程序,将温度从华氏温度转换为摄氏温度,并为用户提供继续提供温度的选项,直到他们选择不提供为止。这是我的密码使用Java进行温度转换的用户返回,java,Java,我想创建一个程序,将温度从华氏温度转换为摄氏温度,并为用户提供继续提供温度的选项,直到他们选择不提供为止。这是我的密码 import java.util.Scanner; public class TempConversions { private static int temperature; private static int fahrenheit; public TempConversions () { fahrenheit = 0; temperature = 0; }
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();
}
}
}
您可以使用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();
}
}
}
所以我要做的就是指定一个常量作为退出变量,例如
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循环上执行do-while循环的逻辑是,您需要至少执行一次。
如果您不知道或您知道用户想要循环多少次,您将使用另一种循环。好的,您的问题是什么?这段代码以什么方式不符合您的要求?顺便说一句,您似乎正在将华氏温度转换为摄氏温度,然后将结果打印为华氏温度。是的,但程序在1次转换后结束。我想让它询问用户是否想继续,如果是,那么他们输入另一个数字进行转换,如果不是,那么他们可以选择退出。好了,我得到了我想要它做的一切,除了最后。我希望用户输入00以结束程序,或输入F以继续并输入另一个值以进行转换。在循环结束时需要if语句。如果选择=='F'显示继续消息,否则显示退出消息您将选择一个char变量,并将常量更改为char