Java- 字符串索引越界异常“字符串索引超出范围”
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4008016/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Java- String index out of bounds exception " String index out of Range"
提问by Pete
I am new to java, and going to bite the bullet by asking what is I am sure, a dumb question. I created some methods, and simply wanted to call them in main. I am getting an error for the while loop in the main method. The compiler is saying " Exception in thread main java.lang.StringIndexOutOfBoundsException: String index out of range:0 at java.lang.String.charAt(String.java:686) at Project3.main(Project3.java:61)
我是 Java 新手,我会硬着头皮问我确信什么,这是一个愚蠢的问题。我创建了一些方法,只是想在 main 中调用它们。我在 main 方法的 while 循环中遇到错误。编译器说“线程 main java.lang.StringIndexOutOfBoundsException 中的异常:String index out of range:0 at java.lang.String.charAt(String.java:686) at Project3.main(Project3.java:61)
Any help would be greatly appreciated. Thanks. Full Code is below:
任何帮助将不胜感激。谢谢。完整代码如下:
import javax.swing.JOptionPane;
import java.util.Scanner;
public class Project3
{
public static void main(String[] args)
{
int iScore1; //first variable input by user to calc average
int iScore2; //second variable input by user to calc average
int iScore3; //third variable input by user to calc average
double dAverage; //returned average from the three test scores
char cLetterGrade; //letter grade associated with the average
double dGPA; //the GPA associated with the letter grade
char cIterate = 'Y'; // loop check
String strAgain; //string user inputs after being asked to run again
System.out.print(createWelcomeMessage());
//pause in program
pressAnyKey();
while (cIterate == 'Y')
{
//prompt user for test scores
System.out.print("\n\nPlease enter the first test score: ");
Scanner keys = new Scanner(System.in);
iScore1 = keys.nextInt();
System.out.print("\nPlease enter the second test score: ");
iScore2 = keys.nextInt();
System.out.print("\nPlease enter the third test score: ");
iScore3 = keys.nextInt();
//calculate average from the three test scores
dAverage = calcAverage(iScore1, iScore2,iScore3);
System.out.print("\nThe average of the three scores is: " + dAverage);
//pause in program
pressAnyKey();
//get letter grade associated with the average
cLetterGrade = getLetterGrade(dAverage);
System.out.print("\nThe letter grade associated with the average is " + cLetterGrade);
//pause in program
pressAnyKey();
//get the GPA associated with the letter grade
dPGA = calcGPA(cLetterGrade);
System.out.print("\nThe GPA associated with the GPA is "+ dGPA);
//pause in program
pressAnyKey();
System.out.print("\nDo you want to run again?(Y or N):_\b");
strAgain = keys.nextLine;
strAgain = strAgain.toUpperCase();
cIterate = strAgain.charAt(0);
}//end while
//display ending message to user
System.out.print(createEndingMessage());
}//end main method
}//end class Project3
public static String createWelcomeMessage()
{
String strWelcome;
strWelcome = "Why hello there!\n";
return strWelcome;
}//end createWelcomeMessage()
public static String createEndingMessage()
{
String strSalutation;
strSalutation = "See you later!\n";
return strSalutation;
}//end createEndingMessage()
public static void pressAnyKey()
{
JOptionPane.showMessageDialog(null, "Press any key to continue: ");
}//end pressAnyKey()
public static int getTestSCore()
{
int iScore;
System.out.print("Enter a test score: ");
Scanner keys = new Scanner(System.in);
iScore = keys.nextInt();
return iScore;
}//end getTestSCore()
public static int calcAverage(int iNum1, int iNum2, int iNum3)
{
double dAverage;
dAverage = ((double)iNum1 + (double)iNum2 + (double)iNum3) / (double)3.0;
return dAverage;
}//end calcAverage(int iNum1, int iNum2, int iNum3)
public static char getLetterGrade(double dGrade)
{
char cLetter;
if (dGrade <60)
{
cLetter = 'F';
}
else if (dGrade >=60 && dGrade <70)
{
cLetter = 'D';
}
else if (dGrade >=70 && dGrade <80)
{
cLetter = 'C';
}
else if (dGrade >=80 && dGrade <90)
{
cLetter = 'B';
}
else if (dGrade >=90)
{
cLetter = 'A';
}
return cLetter;
}//end getLetterGrade(double dGrade)
public static double calcGPA(char cLetterGrade)
{
double dGPA;
if (cLetterGrade == 'A')
{
dGPA = 4.0;
}
else if (cLetterGrade == 'B')
{
dGPA = 3.0;
}
else if (cLetterGrade == 'C')
{
dGPA = 2.0;
}
else if (cLetterGrade == 'D')
{
dGPA = 1.0;
}
else
{
dGPA = 0.0;
}
return dGPA;
}//end calcGPA(char cLetterGrade)
回答by Jorn
The problem is caused by this line:
问题是由这一行引起的:
cIterate = strAgain.charAt(0);
The string apparently does not have a character at index 0, in other words, it is empty. You may want to check the user input and ask again if none was supplied.
该字符串显然在索引 0 处没有字符,换句话说,它是空的。您可能想要检查用户输入并再次询问是否没有提供。
回答by sepp2k
You're reading three ints using scanner.nextInt()
. Since nextInt
does not consume any whitespace or newline after the read token, that means that if the user enters a number and presses enter, there's still a linebreak in the stream.
您正在使用scanner.nextInt()
. 由于nextInt
在读取标记后不消耗任何空格或换行符,这意味着如果用户输入一个数字并按 Enter,流中仍然有一个换行符。
So when you call nextLine
later it just reads that linebreak and returns the empty string.
因此,当您nextLine
稍后调用时,它只会读取该换行符并返回空字符串。
Since calling charAt
on an empty string will cause an out of bounds error, you get the error you get.
由于调用charAt
空字符串会导致越界错误,因此您会得到错误。
To fix this, either use next
instead of nextLine
, which will read the next word (consuming any whitespace before it), instead of the next line, or call nextLine
twice. Once to consume the linebreak and once to read the actual line.
要解决此问题,请使用next
代替nextLine
,它将读取下一个单词(消耗它之前的任何空格),而不是下一行,或者调用nextLine
两次。一次消耗换行符,一次读取实际行。
You should still check whether the user enters an empty line though.
您仍然应该检查用户是否输入了空行。
回答by Natsu Dragneel
If you move line 67 or so, it's the line that ends the class. Move it to the end, and that brings it down to three errors. One of those three errors is a misspelling, the one about keys.nextLine needs () --> keys.nextLine() and the last error is that the method header returns an int, not a double. Doing this does generate another error, but if you set cLetter to a space in single quotes, ' ' then the code compiles.
如果您移动第 67 行左右,则该行结束课程。把它移到最后,这将它归结为三个错误。这三个错误之一是拼写错误,一个关于 keys.nextLine 需要 () --> keys.nextLine() ,最后一个错误是方法头返回一个 int,而不是一个 double。这样做确实会产生另一个错误,但如果将 cLetter 设置为单引号中的空格, ' ' 然后代码编译。