2015-09-09 45 views
0

代碼:嘿即時得到的索引超出範圍的可變

System.out.println("Please choose an option"); 
Choice=user_input.next().charAt(0); 
//entering 1 as char thats when it displayes "Do you want to open" then gives me index out of bonds error 
if (Choice=='1'){ 
    System.out.println("Do you want to open a 'c'hecking Account or 's'aving account"); 
    Choice=user_input.nextLine().charAt(0); 
    if (Choice=='c'||Choice=='C'){ 
     System.out.println("You want to open a checking account"); 
     System.out.println("Please enter your name,Account number and balance"); 

輸出

Please choose an option 
1 

Do you want to open a 'c'hecking Account or 's'aving account 

Exception in thread "main" java.lang.StringIndexOutOfBoundsException: 
String index out of range: 0 
    at java.lang.String.charAt(Unknown Source) 
    at BankOnlineSystem_Ayoub.main(BankOnlineSystem_Ayoub.java:18) 
+0

您鍵入1,然後,對不對?所以下一個項目是1,然後後面的行就是,即一個空白行 – immibis

回答

1

變化

Choice=user_input.next().charAt(0); 

Choice=user_input.nextLine().charAt(0); 

阻止您的user_input.nextLine()返回空字符串。

+0

所以它最好避免使用下一個函數。相反,我總是使用nextLine嗎? – Chug

+0

@chug next()用於從當前行讀取單個字符串標記。如果你想閱讀整行,你應該更喜歡nextLine。 – Eran