Java - Строковый индекс вне границ исключение «Строковый индекс вне диапазона» - PullRequest
0 голосов
/ 24 октября 2010

Я новичок в Java, и собираюсь укусить пулю, задав вопрос, что я уверен, тупой вопрос.Я создал несколько методов и просто хотел вызвать их в main.Я получаю сообщение об ошибке цикла while в основном методе.Компилятор говорит: «Исключение в основном потоке java.lang.StringIndexOutOfBoundsException: индекс строки вне диапазона: 0 в java.lang.String.charAt (String.java:686) в Project3.main (Project3.java:61)

Любая помощь будет принята с благодарностью. Спасибо. Полный код ниже:

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)

Ответы [ 3 ]

5 голосов
/ 24 октября 2010

Вы читаете три целых, используя scanner.nextInt(). Поскольку nextInt не использует пробелы или символы новой строки после считываемого токена, это означает, что, если пользователь вводит число и нажимает клавишу ввода, в потоке все еще остается разрыв строки.

Поэтому, когда вы вызываете nextLine, позже он просто читает этот разрыв строки и возвращает пустую строку.

Поскольку вызов charAt для пустой строки приведет к ошибке выхода за границы, вы получите ошибку, которую вы получите.

Чтобы исправить это, используйте next вместо nextLine, который будет читать следующее слово (занимая все пробелы перед ним), вместо следующей строки, или дважды вызовите nextLine Один раз потреблять перевод строки и один раз прочитать фактическую строку.

Вы все равно должны проверить, вводит ли пользователь пустую строку.

0 голосов
/ 05 декабря 2017

Если вы переместите строку 67 или около того, это строка, которая завершает класс. Переместите его до конца, и это сводит его к трем ошибкам. Одна из этих трех ошибок - ошибка, одна из которых связана с keys.nextLine needs () -> keys.nextLine (), а последняя ошибка заключается в том, что заголовок метода возвращает целое число, а не двойное число. Это вызывает еще одну ошибку, но если вы установите для cLetter пробел в одинарных кавычках, '', то код скомпилируется.

0 голосов
/ 24 октября 2010

Проблема вызвана этой строкой:

cIterate = strAgain.charAt(0);

Строка, очевидно, не имеет символа с индексом 0, другими словами, она пуста.Возможно, вы захотите проверить пользовательский ввод и снова спросить, не было ли ничего предоставлено.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...