2015-10-15 157 views
0
System.out.println("What hero are you playing?"); 
Scanner console = new Scanner(System.in); 
Scanner value = new Scanner(System.in); 
String character = console.next(); 
String[] hero = {"x1", "x2", "x3", "x4"}; 

if(Arrays.asList(hero).contains(character)) { 
    System.out.println("hero selected: "+ character); 
} 
else { 
    System.out.println("hero not found"); 
} 

我希望它運行,直到一個正確的英雄名字被髮。如果輸入了錯誤的名字,它應該再次提出要求。循環直到正確的輸入

回答

0

您正在嘗試循環的次數未知量。 (直到滿足您定義的條件)。你正在尋找'while'循環。既然你總是想在輸入不正確的名字時做同樣的事情,這部分代碼應該放在while循環中。當輸入正確的名稱時,您想要在代碼中移動。因此,將該事件的處理放置在循環外部:

System.out.println("What hero are you playing?"); 
Scanner console = new Scanner(System.in); 
/**you have a second scanner, but it's using the same input source. You 
should only have one scanner for System.in, maybe call the variable userInput**/ 
Scanner value = new Scanner(System.in); 
//String character = console.next(); you only take input from the user once, this needs to go into a loop. 
String character; //do this instead 
String[] hero = {"x1", "x2", "x3", "x4"}; 
while(!Arrays.asList(hero).contains(character = console.next())) {//changed to a while loop. This will keep running until the condition evaluates to false. 
    System.out.println("hero not found"); //notice the '!' in the condition check. this means if next console input is NOT contained in the hero array. 
} 
System.out.println("hero selected: "+ character); //if we're no longer in the loop, it means we found a correct hero name. 
0

嘗試這樣的事情

System.out.println("What hero are you playing?"); 
    Scanner console = new Scanner(System.in); 
    Scanner value = new Scanner(System.in); 
    String character; 
    String[] hero = {"x1", "x2", "x3", "x4"}; 
    do{ 
     character = console.next(); 
     if(Arrays.asList(hero).contains(character)) { 
      System.out.println("hero selected: "+ character); 
      break; 
     } 
     else {System.out.println("hero not found"); 
     }  
    }while (true); 
相關問題