-1

我知道这是一个简单的问题,但我是 Java 新手,我很迷茫。如果用户没有输入“是”或“否”并返回到它要求进行另一个计算。我知道这是基本的,我尽我所能寻找答案,但我对 Java 术语的了解还不够。如果您能帮助我,我将不胜感激!

PS有人向我指出,我的变量不应该以大写字母开头,我知道并且将来不会这样做。

    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;                      
        }
       }  
4

2 回答 2

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语句。对于这个简单的用例,我们可以利用fall throughcase 语句的效果将可接受的值扩展到 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;
}
于 2013-09-29T17:09:23.820 回答
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;

       }
于 2013-09-29T17:02:29.740 回答