2017-06-15 57 views
-2

是否有可能使用while循环不断使我的代码循环直到用户选择提示结束代码?这是我的代码,如果你想看到上下文。代码本身并不是那么重要,我只想知道我是否可以在我的方法中添加一个while循环,以允许用户在调用方法后始终返回到printMenu()。Java如何使用方法返回后返回

import java.io.*; 
    public class Plane { 
    /*Plane's seats will resemble 
    * | [A1] [B1] [C1] [D1] [E1] | 
    * | [A2] [B2] [C2] [D2] [E2] | 
    */ 
    public static void main(String[] args) { 
    InputStreamReader inStream = new InputStreamReader(System.in); 
    BufferedReader bufRead = new BufferedReader(inStream); 

    printMenu(); 
    try { 
     String choiceString = bufRead.readLine(); 
     int choiceInt = Integer.parseInt(choiceString); 
     if (choiceInt == 1) { 
     makeSeatReservation(); 
     } 

     if (choiceInt == 2) { 
     try { 
     Cancel(); 
     } catch (IOException e) { 
     e.printStackTrace(); 
     } 
     } 

     if (choiceInt == 3) { 
     printSeating(); 
     } 

     if (choiceInt == 4) { 
     cancelFlights(); 
     } 

     if (choiceInt == 5) { 
     FlightTakeoff(); 
     } 

     if (choiceInt == 6) { 
     System.out.println("Program will terminate"); 
     System.exit(0); 
     } else { 
     System.out.println("Invalid Number"); 
     } 
    } catch (IOException e) { 
     e.printStackTrace(); 
    } 
    } 
    /** 
    * Menu 
    */ 

    public static void printMenu() { 
    System.out.println(" Booking Menu "); 
    System.out.println("    "); 
    System.out.println("Please press the corresponding numbers to perform a specific action"); 
    System.out.println("1. Make a reservation"); 
    System.out.println("2. Cancel a reserved seat"); 
    System.out.println("3. View the current available/reserved seats 
     remaining "); 
     System.out.println("4. Cancel the flight"); System.out.println("5. Flight takeoff"); System.out.println("6. Quit"); //This will end my code 
    } 
+1

你需要正确格式化你的代码。这是非常难以阅读的。 – Carcigenicate

+0

是的,这完全有可能。显示你已经尝试了什么,以便我们知道你的目标是什么。 – Carcigenicate

+0

好的问题编辑问题 –

回答

0

你可以做这样的事情:

boolean exit = false; 
while (!exit) { 
    printMenu(); 
    try { 
     String choiceString = bufRead.readLine(); 
     int choiceInt = Integer.parseInt(choiceString); 
     if (choiceInt == 1) { 
     makeSeatReservation(); 
     } 

     if (choiceInt == 2) { 
     try { 
     Cancel(); 
     } catch (IOException e) { 
     e.printStackTrace(); 
     } 
     } 

     if (choiceInt == 3) { 
     printSeating(); 
     } 

     if (choiceInt == 4) { 
     cancelFlights(); 
     } 

     if (choiceInt == 5) { 
     FlightTakeoff(); 
     } 

     if (choiceInt == 6) { 
     System.out.println("Program will terminate"); 
     System.exit(0); 
     } else { 
     System.out.println("Invalid Number"); 
     } 
    } catch (IOException e) { 
     e.printStackTrace(); 
    } 
    } 

我添加了一个名为“退出”的变量,并把while循环在你的代码。所有你需要做的就是像这样:exit = true;无论你希望用户能够退出循环。这是你要求的吗?让我知道。

1

我认为kobiF解决方案已经足够好了。我只想添加一些更好的方法。但这只是我的“风格”。 我试图改变如果是一个开关,并做同样的事情,或者最好把它放在一个do..while循环,因为你想这样做,除非一次