将切换案例返回到Java中的主程序

时间:2013-09-29 16:44:01

标签: java

我知道这是一个简单的问题,但我是Java新手,我很丢失。如果用户没有输入是或否,那么在我的程序中剩下要做的就是在我的程序中输出一个类似“无效输入,再试一次”的消息,然后返回到它要求另一个计算。我知道它是基本的,我尽力寻找答案,但我根本不了解java术语。如果你能帮助我,我会非常感激!

P.S.It向我指出,我的变量不应该以大写字母开头,我知道并且将来也不会这样做。

    System.out.println(" The purpose of this program is to calculate the speed of sound through several mediums.\n The program user will input a distance in feet followed by a mediumd and the program will output the speed in feet per second and miles per hour\n");
    //declare variables

    Scanner keyboard = new Scanner(System.in);

    final double Air = 1126.1;

    final double Water = 4603.2;

    final double Steel = 20013.3;

    final double Earth = 22967.4;

    double OneFootPerSecond = .68181818182;

    double Distance;

    double AirSpeed;

    double WaterSpeed;

    double SteelSpeed;

    double EarthSpeed;

    boolean shouldContinue = true;

    while (shouldContinue == true){ 

    System.out.print(" What is the distance in feet:" );
    //ask the user to input variables


        while (!keyboard.hasNextDouble()){
        System.out.println("Please enter a valid numeric value, try again: ");
        keyboard.next();
        }
        Distance =keyboard.nextDouble();
        {
        System.out.print("Input the media: Air, Water, Steel, or Earth: ");
        String Input = keyboard.next();   



        switch(Input.toLowerCase())

         {

            case "air":
            AirSpeed = Distance/Air;
            System.out.print("\n \nThe time to for sound to travel ");
            System.out.print(Distance);
            System.out.print(" feet through AIR" +"\n");
            System.out.printf("%.6f", AirSpeed);
            System.out.print(" seconds or ");
            System.out.printf("%.1f", OneFootPerSecond*Air);
            System.out.print(" miles per hour."); 
            System.out.print("\n \nEnter Yes for another calculation, else No: ");
            String Another = keyboard.next();
            Another.toLowerCase();
           if (Another.equals("no")){
               shouldContinue = false;
                              }
          if (!Another.equals("no"))
              if (!Another.equals("yes"))
              {System.out.print("Invalid.");


              }


            break;



     case "water":
            WaterSpeed = Distance/Water;
            System.out.print("\nThe time to for sound to travel ");
            System.out.print(Distance);
            System.out.print(" feet through WATER" +"\n");
            System.out.printf("%.6f",WaterSpeed);
            System.out.print(" seconds or ");
            System.out.printf("%.1f", OneFootPerSecond*Water);
            System.out.print(" miles per hour."); 
            System.out.print("\n \nEnter Yes for another calculation, else No: ");
            Another = keyboard.next();
            Another.toLowerCase();
             if (Another.equals("yes")){
               shouldContinue = false;

           }
    break;

     case "steel":
            SteelSpeed = Distance/Steel;
            System.out.print("\nThe time to for sound to travel ");
            System.out.print(Distance);
            System.out.print(" feet through STEEL" +"\n");
            System.out.printf("%.6f",SteelSpeed);
            System.out.print(" seconds or ");
            System.out.printf("%.1f",  OneFootPerSecond*Steel);
            System.out.print(" miles per hour."); 
            System.out.print("\n \nEnter Yes for another calculation, else No: ");
            Another = keyboard.next();
            Another.toLowerCase();
             if (Another.equals("yes")){
               shouldContinue = false;

           }
    break;     

          case "earth":
            EarthSpeed = Distance/Water;
            System.out.print("\nThe time to for sound to travel ");
            System.out.print(Distance);
            System.out.print(" feet through EARTH" +"\n");
            System.out.printf("%.6f",EarthSpeed);
            System.out.print(" seconds or ");
            System.out.printf("%.1f",  OneFootPerSecond*Earth);
            System.out.print(" miles per hour."); 
            System.out.print("\n \nEnter Yes for another calculation, else No: ");
            Another = keyboard.next();
            Another.toLowerCase();
             if (Another.equals("yes")){
               shouldContinue = false;

           }
    break;
    default :
            System.out.print("Invalid. Re-run the program. ");                  
     break;                      
        }
       }  

2 个答案:

答案 0 :(得分:2)

考虑到您要为每种情况请求另一个计算,以防止重复的代码移动提示以进行其他处理,并将其放在switch语句之后。然后提供一种方法来继续提示用户,直到他们输入可接受的输入。

    public boolean promptForContinue(final Scanner keyboard) {
    boolean isValid = false;
    String userInput = "";
    do {
        userInput = keyboard.next();

        isValid = userInput.matches("Yes|No");

        if (!isValid) {
            System.out.println("Invalid entry.");
        }
    } while (!isValid);

    return userInput.equals("Yes") ? true : false;
}

编辑:替代实施消除了对额外局部变量的需求并删除了regex的使用。此外,.toLowerCase()的添加扩展了可接受的输入,而无需额外的case语句。对于这个简单的用例,我们可以利用case语句的fall through效果将可接受的值扩展为8。

 private static boolean promptForContinue(final Scanner keyboard)
 {
    do
    {
     System.out.print("Continue (Yes/No) ?");
     final String userInput = keyboard.next().toLowerCase();

     switch(userInput)
     {
       case "y":
       case "yes": return true;
       case "n": 
       case "no": return false;
       default : 
         System.out.println("Invalid Entry.");
     }
   }
   while (true);
 }

然后,shouldContinue将在while循环结束时设置为该方法的返回值。

shouldContinue = promptForContinue(keyboard);

将您所拥有的内容与我的建议相结合,该文件应如下所示。此外,我建议将两个计算存储在一个变量中,以便您可以将重复的打印语句移出案例。

public static void main(String[] args)
{
System.out.println(" The purpose of this program is to calculate the speed of sound through several mediums.\n The program user will input a distance in feet followed by a mediumd and the program will output the speed in feet per second and miles per hour\n");
//declare variables

Scanner keyboard = new Scanner(System.in);

final double Air = 1126.1;

final double Water = 4603.2;

final double Steel = 20013.3;

final double Earth = 22967.4;

double OneFootPerSecond = .68181818182;

double Distance;

double AirSpeed;

double WaterSpeed;

double SteelSpeed;

double EarthSpeed;

boolean shouldContinue = true;

while (shouldContinue == true)
{

  System.out.print(" What is the distance in feet:");
  //ask the user to input variables


  while (!keyboard.hasNextDouble())
  {
    System.out.println("Please enter a valid numeric value, try again: ");
    keyboard.next();
  }

  Distance = keyboard.nextDouble();

  System.out.print("Input the media: Air, Water, Steel, or Earth: ");
  String Input = keyboard.next();

  switch (Input.toLowerCase())
  {

    case "air":
      AirSpeed = Distance / Air;
      System.out.print("\n \nThe time to for sound to travel ");
      System.out.print(Distance);
      System.out.print(" feet through AIR" + "\n");
      System.out.printf("%.6f", AirSpeed);
      System.out.print(" seconds or ");
      System.out.printf("%.1f", OneFootPerSecond * Air);
      System.out.println(" miles per hour.");

      break;

    case "water":
      WaterSpeed = Distance / Water;
      System.out.print("\nThe time to for sound to travel ");
      System.out.print(Distance);
      System.out.print(" feet through WATER" + "\n");
      System.out.printf("%.6f", WaterSpeed);
      System.out.print(" seconds or ");
      System.out.printf("%.1f", OneFootPerSecond * Water);
      System.out.println(" miles per hour.");

      break;

    case "steel":
      SteelSpeed = Distance / Steel;
      System.out.print("\nThe time to for sound to travel ");
      System.out.print(Distance);
      System.out.print(" feet through STEEL" + "\n");
      System.out.printf("%.6f", SteelSpeed);
      System.out.print(" seconds or ");
      System.out.printf("%.1f", OneFootPerSecond * Steel);
      System.out.println(" miles per hour.");


      break;

    case "earth":
      EarthSpeed = Distance / Water;
      System.out.print("\nThe time to for sound to travel ");
      System.out.print(Distance);
      System.out.print(" feet through EARTH" + "\n");
      System.out.printf("%.6f", EarthSpeed);
      System.out.print(" seconds or ");
      System.out.printf("%.1f", OneFootPerSecond * Earth);
      System.out.println(" miles per hour.");

      break;
    default:
      System.out.println("Invalid. Re-run the program. ");
      break;
  }
  shouldContinue = promptForContinue(keyboard);
 }

}

private static boolean promptForContinue(final Scanner keyboard)
{
 boolean isValid = false;
 String userInput = "";
 do
 {
   System.out.print("Continue (Yes/No) ?");
   userInput = keyboard.next();

   isValid = userInput.matches("Yes|No");

   if (!isValid)
   {
    System.out.println("\nInvalid entry.");
   }
 }
 while (!isValid);

 return userInput.equals("Yes") ? true : false;
}

答案 1 :(得分:0)

你有一个逻辑问题

        System.out.print("\n \nEnter Yes for another calculation, else No: ");
        Another = keyboard.next();
        Another.toLowerCase();
         if (Another.equals("yes")){
           shouldContinue = false;

       }

如果用户键入yes,则此代码将退出循环,您的if应为:

        if (Another.equals("yes")){
           shouldContinue = true;

       }
       else 
       if (Another.equals("no")){
           shouldContinue = false;

       }
       else 
       {
           System.out.print("Invalid input");
           shouldContinue = true;

       }