2015-10-11 52 views
1

嘿傢伙我想創建一個循環,直到用戶輸入正確的字符選擇。當我輸入錯誤的選擇時,我得到錯誤java.lang.NullPointerException。這可能與我輸入的方式有關,但如果我不需要,我不想改變它。選擇是該班的私人成員。java.lang.NullPointerException表單用戶輸入

char wf() { 
    Scanner input = new Scanner(System.in); 
    System.out.println("What is your choice? (x/o)"); 
    choice = input.findInLine(".").charAt(0); 

    while (choice != 'x' && choice != 'o') { 
     System.out.println("You must enter x or o!"); 
     choice = input.findInLine(".").charAt(0); 
    } 

    return choice; 
}//end wf 
+1

'findLineAt'是否返回'null'?如果是這樣,那就是問題所在,因爲你之後立即調用'charAt'。如果'findLineAt'爲'null',那麼你將無法調用方法,因爲沒有對象調用方法(而不是null),因此NPE。 –

+1

既然很清楚'findLineAt'返回'null',你只需要明白爲什麼。你可以通過閱讀JavaDoc並調試這個方法來做到這一點,看看會發生什麼。 – Tom

回答

1

變化如下(我已經測試此代碼)功能:

char wf() { 
    Scanner input = new Scanner(System.in); 
    System.out.println("What is your choice? (x/o)"); 
    char choice = input.findInLine(".").charAt(0); 

    while (choice != 'x' && choice != 'o') { 
     System.out.println("You must enter x or o!"); 
     choice = input.next().charAt(0); 
    } 

    return choice; 
}//end wf 
+1

謝謝工作完美! – KingKrypton

+0

非常感謝:-) –

1

檢查input.findInLine( 「」),看它是否爲空。如果你沒有預期的輸入,它不會返回任何東西..

1

改變你的代碼像下面

char wf() { 
Scanner input = new Scanner(System.in); 
System.out.println("What is your choice? (x/o)"); 
if(input.findInLine(".") !=null){ 
choice = input.findInLine(".").charAt(0); 
while (choice != 'x' && choice != 'o') { 
    System.out.println("You must enter x or o!"); 
    choice = input.findInLine(".").charAt(0); 
} 
} 
return choice; 
}//end wf 
+1

你能解釋一下爲什麼它應該起作用嗎? – Tom