2011-11-26 75 views
1

我在获取Java读取字符串中的第一个字符时遇到了一些麻烦。我在这里包括了代码到这里(代码超出这个,我认为,根本不相关):无法读取字符串中的字符(Java)

import java.util.Scanner; 
public class SeveralDice { 

    public static void main(String[] args) { 

     Scanner input = new Scanner(System.in); 

     System.out.print("How many dice do you want to use? "); 

     int numberOfDice = input.nextInt(); 

     SeveralDice game = new SeveralDice(numberOfDice); 

     System.out.print("You have 0 points. Another try(y/n)? "); 

     boolean turn = true; 
     String answerInput; 
     char answer; 
     int lastValue = 0; 

     while (turn) { 
      answerInput = input.nextLine(); 
      answer = answerInput.charAt(0); 
      if (answer == 'y') {. . . . . 

然后代码继续。但是,当我运行程序时,出现错误:

Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 0 
    at java.lang.String.charAt(Unknown Source) 
    at SeveralDice.main(SeveralDice.java:25)* 

25行是行answer = answerInput.charAt(0);。所以显然这里出了问题。任何帮助将不胜感激!

回答

1

看来,输入“多少个骰子...”的整数也会触发nextLine()读取一个空行(因为您在写完整数后按回车键),所以您正在阅读有0个字符的字符串。我建议你更换:

int numberOfDice = input.nextInt(); 

int numberOfDice = Integer.parseInt(input.nextLine()); 
+0

之后简单地致电input.nextLine()非常感谢!这工作:) – Kristian

+0

@Kristian:很高兴帮助。如果它解决了您的问题,请不要忘记选择接受的答案。 :) – Tudor

2

这是因为当你这样做:

int numberOfDice = input.nextInt(); 

您阅读用户进入int\n仍然是在输入流中。

循环中第一次调用input.nextLine()标记为\n,因此它读取的是空行,因此answerInput的长度为零。 nextLine()nextInt()不同,因为它将整行读入String,并从输入中去除尾部\n

正如其他人所发布的,检查answerInput的长度将解决问题。您也可以在获得您的intnextInt()

+0

非常感谢!这真的很有用!我一直在努力理解这一点,这使得现在很有意义:) – Kristian