2016-04-28 9 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フロー制御EXITコードが入力されるまで:

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; 
} 
関連する問題