我似乎无法弄清楚输入while循环的位置或内容。 一切正常,但在我输入转换后,如何让它问我是否要输入另一个问题。
import java.util.Scanner;
public class DistanceConversion
{
public static void showKilometers(double meters)
{
double kilometers = meters * 0.001;
System.out.println(meters +" meters is " + kilometers + " kilometers.");
}
public static void showInches(double meters)
{
double inches = meters * 39.37;
System.out.println(meters +" meters is " + inches + " inches.");
}
public static void showFeet(double meters)
{
double feet = meters * 3.281;
System.out.println(meters +" meters is " + feet + " feet.");
}
public static void quitProgram()
{
System.out.println("Goodbye!");
System.out.println(0);
}
public static void showMenu()
{
System.out.println(" 1. Convert to kilometers ");
System.out.println(" 2. Convert to inches ");
System.out.println(" 3. Convert to feet ");
System.out.println(" 4. Quit the program ");
System.out.println(" ");
}
public static void main (String [] args)
{
double meters;
int choice;
Scanner scan = new Scanner (System.in);
System.out.print("Enter a distance in meters: ");
meters = scan.nextDouble();
showMenu();
choice = scan.nextInt();
switch(choice)
{
case 1:showKilometers(meters);
break;
case 2:showInches(meters);
break;
case 3:showFeet(meters);
break;
case 4:quitProgram();
}
}
}
答案 0 :(得分:1)
你想重复一下?整个计划?然后附上“整个程序”又名。带有while循环的主逻辑,检查输入是否等于4或其他任意退出int。
在顶部声明“int choice”,然后将其余部分括起来。
while(choice >= 1 && choice <=3)
{
//main-method code here
}
编辑(为清晰起见):
int choice = 0;
while(choice != 4)
{
double meters;
Scanner scan = new Scanner (System.in);
System.out.print("Enter a distance in meters: ");
meters = scan.nextDouble();
showMenu();
choice = scan.nextInt();
switch(choice)
{
case 1:showKilometers(meters);
break;
case 2:showInches(meters);
break;
case 3:showFeet(meters);
break;
case 4:quitProgram();
}
}