我在獲取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);
。所以顯然這裏出了問題。任何幫助將不勝感激!
之後簡單地致電
input.nextLine()
非常感謝!這工作:) – Kristian@Kristian:很高興幫助。如果它解決了您的問題,請不要忘記選擇接受的答案。 :) – Tudor