我在获取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