2011-11-26 50 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