如何在顯示「無效選擇」後再次顯示菜單?初學Java:如何讓它在「無效選擇」後再次顯示菜單
現在,當輸入數字< 1或> 4時,它只顯示「無效選擇」。
理想我希望它顯示
"Invalid selection
/nMETER CONVERSION
1) Convert to Kilometers
2) Convert to Inches
3) Convert to Feet
4) Quit the Program
Please make a selection:"
這裏是我的代碼
import java.util.Scanner;
import java.text.DecimalFormat;
public class Homework8bbb
{
//create main
public static void main(String[]args)
{//open main method
int selection;
double meters;
Scanner keyboard = new Scanner(System.in);
DecimalFormat format = new DecimalFormat("##.00");
//call showMenu method
//DISPLAY showMenu method
do
{
showMenu();
//get user [selection]
selection = keyboard.nextInt();
//validate selection
do {
if (selection < 1 || selection > 4)
{
System.out.print("Invalid selection\n");
selection = keyboard.nextInt();
}
}while(selection < 1 || selection > 4);
//get [meters]
System.out.print("How many meters?\n");
meters = keyboard.nextInt();
//validate meters: do not allow negative meters
while (meters < 0)
{
System.out.print("Invalid Selection. Please enter a positive number:\n");
meters = keyboard.nextInt();
}
switch (selection)
{
case 1: calcKilometers(meters);
break;
case 2: calcInches(meters);
break;
case 3: calcFeet(meters);
break;
case 4:
break; }
}while(selection != 4);
}
public static void showMenu()
{
System.out.print("\n"
+ "METER CONVERSION\n"
+ " 1) Convert to Kilometers\n"
+ " 2) Convert to Inches\n"
+ " 3) Convert to Feet\n"
+ " 4) Quit the Program\n"
+ " Please make a selection:\n");
}
//calcKilometers method
public static double calcKilometers(double meters)
{
double kilometers;
kilometers = meters * 0.001;
System.out.println(meters + " meters is " +
kilometers + " kilometers.");
return kilometers;
}
//calcInches method
public static double calcInches(double meters)
{
double inches;
inches = meters * 39.37;
System.out.println(meters + " meters is " +
inches + " inches.");
return inches;
}
//calcFeet method
public static double calcFeet(double meters)
{
double feet;
feet = meters * 3.281;
System.out.println(meters + " meters is " +
feet + " feet.");
return feet;
}
}//close class
開始的就是你在IDE中得到錯誤???我只看到2個警告:***「掃描儀鍵盤和DecimalFormat格式從未使用過」*** –