强制用户在选项2之前选择选项1

时间:2016-11-21 13:39:11

标签: java

我想强制用户选择1,然后才能继续选择2,任何帮助都会受到赞赏。 (注意我到目前为止只执行过if,while,for,do .... while,java中的方法和数组)

Scanner sc = new Scanner(System.in);   

int[] ages = new int[3];
int choice;
do {
   System.out.println("Average Age program");
   System.out.println("Enter 1 to enter ages");
   System.out.println("Enter 2 to calculate the average Age");
   System.out.println("Enter 0 to Exit");
   choice = sc.nextInt();
   switch(choice) {
       case 1:
           acceptAges(ages);
           break;

       case 2:
           averageAge(ages);
           break;

       default:
           System.out.print("invalid option");

    } 

  } while(choice != 0);
}

1 个答案:

答案 0 :(得分:0)

2被选中至少一次之前,您无法显示选择1

 Scanner sc = new Scanner(System.in);   

 int[] ages = new int[3];
 int choice;
 boolean is2Enabled=false,
 do{
   System.out.println("Average Age program");
   System.out.println("Enter 1 to enter ages");
   if(is2Enabled)
     System.out.println("Enter 2 to calculate the average Age");
   System.out.println("Enter 0 to Exit");
   choice=sc.nextInt();
   switch(choice)       
   {
       case 1:
       acceptAges(ages);
       is2Enabled=true;
       break;

       case 2:
       if(is2Enabled)
         averageAge(ages);
       else
         System.out.print("invalid option");
       break;

       default:
       System.out.print("invalid option");
    } 
  }while(choice != 0);
}