2012-04-30 57 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