2012-04-30 56 views
0

好的,所以我似乎無法得到這個工作,雖然很多人告訴我的語法和邏輯是正確的。任何人都可以向我透露我可能會做錯什麼?不能得到charAt(0)的工作

public Scanner in = new Scanner(System.in); 

public void movePlayer() { 
    System.out.print("move: "); 
    String str = in.nextLine(); 

    in.nextLine(); 

    char c = str.charAt(0); 

    if (c == 'l' || c == 'L') { 
     player.moveLeft(); 
    } 
} 

程序被燒焦處c = str.charAt(0);

抓而我正在被返回此錯誤:

java.lang.StringIndexOutOfBoundsException: 字符串索引超出範圍:0(java.lang中.String)

+1

Aaaaaand ...你嘗試檢查如果str不爲空? – Raveline

+1

這意味着str是空的(str ==「」),所以在0處沒有字符。 – assylias

+2

不是「not null」,空,對不起。爲什麼你有第二個in.nextLine()沒有任何作用?這是故意的嗎? – Raveline

回答

5

你沒有輸入任何東西,但控制檯,所以str是空的。這就是chatAt(0)拋出異常的原因

+0

@GregKopff錯誤消息是非常清楚的:你只能得到該消息,如果你對空字符串進行charAt。 –

0

這意味着str爲空。你應該檢查它是不是null而不是空的。

if (str != null && !str.isEmpty()) { 
... 
} 
+0

感謝大家的幫助:)把它分類! – UMG90

3

你不想使用nextLine()。你想使用next()

String str = in.next(); 

這是nextLine()

Advances this scanner past the current line and returns the input that was skipped. This method returns the rest of the current line, excluding any line separator at the end. The position is set to the beginning of the next line.

的Javadoc你想next()代替:

Finds and returns the next complete token from this scanner. A complete token is preceded and followed by input that matches the delimiter pattern. This method may block while waiting for input to scan, even if a previous invocation of hasNext() returned true.

這將阻止你消耗空行和引發異常。

0

這就是RYT ..因爲當u嘗試第0位獲得char然後怎麼把F的大小陣列是它會拋出一個異常0

可以是U閱讀本作獲得I/O from the Command Line

0

添加也檢查空字符串和空。你會避免很多頭痛。

0

如果您在控制檯中按Enter鍵,則無論是否輸入文本,Scanner都將被視爲完整行。

在行的開頭按Enter鍵,返回方法Scanner.nextLine()的字符串""

str.charAt(0)之前添加支票str.lenght() > 0