2016-11-21 87 views
1

我想强制用户选择选项1,然后才能继续,并选择选项2以获得任何帮助。 (请注意我只是做了,如果,开关,而对于,做....同时,在Java方法和数组至今)强制用户在选项2之前选择选项1

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); 
} 
+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); 
}