2015-09-16 36 views
2

while複雜條件驗證(檢查是否有輸入,並且如果它的不同來mf)不工作:掃描炭與同時

System.out.println("Insert gender (m/f) "); 
while (!stdin.hasNext() & !(temp = stdin.next()).equals("m") & !(temp.equals("f"))) { 
    System.out.println("try again");stdin.nextLine(); 
} 
inpSexo = temp.charAt(0); 

回答

3

有一個按位比較&操作者在while()條件。
您應該使用邏輯運算符&&

while (stdin.hasNext() && !(temp = stdin.next()).equals("m") && !(temp.equals("f"))) 
+0

這是正確的解決方案。但是,我使用布爾有效,因爲eclipse在temp上引發未初始化的變量。謝謝! – nico91

+0

您可以始終在聲明中初始化變量,例如'String temp =「」;' – MaxZoom

1

下面的代碼片段應該達到你想要什麼:

import java.util.Scanner; 

public class MyClass { 

    public static void main(String[] args) { 

     Scanner s = new Scanner(System.in); 
     boolean valid = false; 
     String input; 

     while (!valid){ 

      System.out.println("Insert gender (m/f) "); 
      input = s.nextLine(); 
      System.out.println("User entered: " + input); 
      if ((input.equalsIgnoreCase("m")) || (input.equalsIgnoreCase("f"))){ 
       valid = true; 
      } 
     } 
    } 
} 
0

您更好地使用這樣的:

class check{ 
    public static void main(String args[]){ 
     try{ 
      DataInputStream in=new DataInputStream(System.in); 
      System.out.print("Enter Sex (M/F): "); 
      String s = in.readLine(); 
      if(s.compareTo("M")==0){ 
       System.out.print("Male"); 
      } 
      if(s.compareTo("F")==0){ 
       System.out.print("F"); 
      } 
      else{ 
       System.out.println("Invalid input!!!") 
      } 
     } 
     catch(IOException e){ 
      System.out.println("IO ERROR !!!"); 
      System.exit(-1); 
     } 
    } 
}