2016-04-28 27 views
1

某人可以編輯我的代碼以使其循環選擇菜單。如果選擇不是5個選項之一,它將提示用戶重新輸入,直到它是一個有效的選項。如果可能的話,解釋也會有幫助。謝謝如何使用循環驗證選擇菜單

這是我的代碼。

import java.util.*; 
public class ShapeLoopValidation 
{ 
    public static void main (String [] args) 
    { 
     chooseShape(); 
    } 

    public static void chooseShape() 
    { 
     while (true){ 
      Scanner sc = new Scanner(System.in); 
      System.out.println("Select a shape number to calculate area of that shape!"); 
      System.out.print("Circle = 1. \nRectangle = 2. \nTriangle = 3. \nExit = 4. \nINPUT : "); 
      int shapeChoice = sc.nextInt(); 
      //while (true) { 
      if (shapeChoice >= 1 && shapeChoice <=4) 
      { 
       if (shapeChoice == 1) 
       { 
        circle(); 
       } 
       else if (shapeChoice == 2) 
       { 
        rectangle(); 
       } 
       else if (shapeChoice == 3) 
       { 
        triangle(); 
       } 
       else if (shapeChoice == 4) 
       { 
        return; 
       } 
      } 
      else 
      { 
       System.out.print("Error : Choice " + shapeChoice + "Does not exist."); 
      } 
     } 

     class Test { 
      int a, b; 

      Test(int a, int b) { 
       this.a = a; 
       this.b = b; 
      } 
     } 
    } 
+0

正確的代碼縮進 – mmuzahid

+0

「有人可以編輯我的代碼,使其循環選擇菜單。如果選擇不是5個選項之一,它將提示用戶重新輸入,直到它是一個有效的選項。「< - 你的代碼已經做到了這一點。什麼問題? –

回答

0

第一:看一看switch

二:讀了一些關於do-while loops(它們通常是很適合這種情況)。

現在,我將如何實現它(但你應該學會如何在這種情況下一個循環):

public static void chooseShape() { 

    boolean valid = false; 
    do { 
     Scanner sc = new Scanner(System.in); 
     System.out.println("Select a shape number to calculate area of that shape!"); 
     System.out.print("Circle = 1. \nRectangle = 2. \nTriangle = 3. \nExit = 4. \nINPUT : "); 
     int shapeChoice = sc.nextInt(); 

     switch (shapeChoice) { 
      valid = true; 
      case 1: 
       circle(); 
       break; 
      case 2: 
       rectangle(); 
       break; 
      case 3: 
       triangle(); 
       break; 
      case 4: 
       return; 
      default: 
       valid = false; 
       System.out.println("Error : Choice " + shapeChoice + "Does not exist."); 
       System.out.println("Please select one that exists.") 
     } 
    } while (!valid) 
} 
0

使用do-while流量控制,直到進入退出代碼:

int shapeChoice; 
do { 
    System.out.println("Select a shape number to calculate area of that shape!"); 
    System.out.print("Circle = 1. \nRectangle = 2. \nTriangle = 3. \nExit = 4. \nINPUT : "); 
    int shapeChoice = sc.nextInt(); 
    // then use if-else or switch 
} while (shapeChoice != 4); 

使用break語句循環在您的代碼中斷代碼如下:

else if (shapeChoice == 4) 
{ 
    break; 
}