初学Java:如何在“无效选择”之后再次显示菜单

时间:2017-06-08 07:10:32

标签: java methods

  

如何在显示“无效选择”后再次显示菜单?

     

现在当一个数字< 1或&gt;输入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

1 个答案:

答案 0 :(得分:0)

你不需要这个循环

   do {
            if (selection < 1 || selection > 4)
            {
                System.out.print("Invalid selection\n");
                continue;
            }
        }while(selection < 1 || selection > 4);

将其替换为

  if (selection < 1 || selection > 4) {
            System.out.print("Invalid selection\n");
            continue;
     }

如果你输入,如果statment continue将带你到循环的开始