2013-09-29 2 views
0

Я знаю, что это простой вопрос, но я новичок в Java и так потерян. Все, что осталось сделать в моей программе, выводит сообщение, в котором говорится о «Недопустимый ввод, повторите попытку» в конце каждого случая в моей программе, если пользователь не вводит ни «да», ни «нет» и возвращается к точке, где он запрашивает другой расчет. Я знаю, что это элементарно, и я искал ответ, насколько мог, но я просто недостаточно знаю терминологию java. Если бы вы могли мне помочь, я бы очень признателен!Как запросить другой ввод, если необходимые параметры не введены?

P.S. Мне было указано, что мои переменные не должны начинаться с заглавных букв, я знаю и не буду этого делать в будущем.

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;      
    } 
    } 
+0

GOTO LABEL (на самом деле, Java не предназначен для использования как это. В нем есть все эти предметы фантазии, например методы. Вы должны разделить код на отдельные методы, это будет легче работать и сэкономит вам много времени.) – MightyPork

ответ

0

Довольно простое решение будет небольшой метод его

позвольте мне показать вам небольшой пример:

public class Main { 
    public static Scanner reader = new Scanner(System.in); 
    public static void main(String... args) { 
     // ... 
     switch(somthing) { 
     case "something": 
      // ... 
      if (!shallContinue()) return; 
      break; 
     case "something else": 
      // ... 
      if (!shallContinue()) return; 
      break; 
     default: 
      // ... 
      if (!shallContinue()) return; 
     } 
    } 

    public static boolean shallContinue() { 
     while (true) { 
      System.out.println("Do you want to continue?"); 
      switch (reader.nextLine().toLowerCase()) { 
      case "yes": 
       return true; 
      case "no": 
       return false; 
      } 
     } 
    } 
} 

Основном вы вызываете функцию и в зависимости от результата вы просто прекратить , Эта функция затем выполняет фактическую связь с пользователем.

Смежные вопросы