我是编程新手,这是我的第一个Java类。 我已经得到了一个代码来计算温度从摄氏度到华氏度,反之亦然,但我无法弄清楚我应该在哪里进入Do While循环以使程序重复或终止。
import java.util.Scanner;
public class PracticeTemp {
private static float f = 0, c = 0;
private static final Scanner scan = new Scanner (System.in);
private static int converChoice = 1;
public static void main(String [] args) {
System.out.println("Press 1 for C->F or 2 for F->C 3 to Quit");
converChoice = scan.nextInt();
if (converChoice == 1)
convertCtoFAndPrint();
else if
(converChoice == 2)
convertFtoCAndPrint();
else if
(converChoice == 3)
System.out.println("The program will now terminate");
System.exit(0);
}
public static void convertFtoCAndPrint() {
System.out.println("Please enter degrees F");
f = scan.nextFloat();
c = (5* (f - 32)) / 9f;
System.out.println(f + " degrees F is " + c + " degrees C.");
}
public static void convertCtoFAndPrint() {
System.out.println("Please enter degrees C");
c = scan.nextFloat();
f = (9 * c + 160) / 5f;
System.out.println(c + " degrees C is " + f + " degrees F.");
}
}
答案 0 :(得分:1)
你可以将它放在主方法体内的代码中,这样每次第一次执行程序时,它会通过显示“按1 ...”消息,重新接受输入等重复。
public static void main(String[] argz){
do{
//Do stuff.
}while(condition);
}
在您的情况下,条件应该是converChoice != 3
的范围,当converChoice
等于3时,该条件将基本停止。
答案 1 :(得分:0)
要使程序重复并从控制台获取输入,您必须包含
#include <stdio.h>
#include <stdlib.h>
int main()
{
int i;
unsigned char temp2[32]= {0x00 ,0x11 ,0x22 ,0x33 ,0x44 ,0x55,0x66 ,0x77 ,0x88 ,0x99 ,0xaa ,0xbb ,0xcc ,0xdd ,0xee ,0xff};
for(i=0;i<16;i++) {
printf("%X", temp2[i] & 0xff);
}
return 0;
}
在用户输入数据的主函数中:
while(true){
//this is an infinite loop
}
或者您可以添加:
public static void main(String [] args) {
while(true) { //this in an infinite loop
System.out.println("Press 1 for C->F or 2 for F->C 3 to Quit");
converChoice = scan.nextInt();
if (converChoice == 1)
convertCtoFAndPrint();
else if (converChoice == 2)
convertFtoCAndPrint();
else if (converChoice == 3) {
System.out.println("The program will now terminate");
System.exit(0);//this stops the program
}
}
}
只要convertChoice(用户输入)不等于3
,就会重复此操作
do{
}while(converChoice!=3);