2017-06-15 53 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循環,因爲你想這樣做,除非一次