这个程序我做错了什么?

时间:2016-01-28 00:34:39

标签: java eclipse

我正在尝试编写代码以将字母等级转换为数字值。我有这段代码,但是当我运行它时,我收到一条错误java.lang.StringIndexOutOfBoundsException

我做错了什么?

以下是代码:

import java.util.Scanner;


public class Lab6Smalls {
  public static void main(String[] args){
    Scanner scan = new Scanner(System.in);

    String grade;
    String letter1;
    String letter2;
    double gpa = 0;

    System.out.print("Enter a letter grade: ");

    grade = scan.nextLine();
    letter1 = grade.substring(0,1);
    letter2 = grade.substring(1,2);

    if (letter1.equals("A") && letter2.equals("+")){
        gpa = 4.3;
    } else if (letter1.equals("A")){
        gpa = 4.0;
    } else if (letter1.equals("B")){
        gpa = 3.0;
    } else if (letter1.equals("C")){
        gpa = 2.0;
    } else if (letter1.equals("D")){
        gpa = 1.0;
    } else if (letter1.equals("F")){
        gpa = 0.0;
    } else {
        System.out.println("The value is invalid.");
    }

    if (!letter1.equals("F")){
        if(letter2.equals("+") && !letter1.equals("A")) gpa += 0.3;
        else if(letter2.equals("-")) gpa -= 0.3;
    }

    System.out.println("The numerical value is " + gpa + ".");
  }
}

2 个答案:

答案 0 :(得分:3)

出现错误,因为A +以外的字母没有第二个值

A +有两个字母

B有一个,所以当你试图找到第二个时,它会中断

C有一个,所以当你试图找到第二个时,它会中断

D有一个当你试图找到第二个时,它就会破坏

您想要在检索之前检查第二个值是否存在。 试试这个

String letter2 = "";
grade = scan.nextLine();
letter1 = grade.substring(0,1);

// Check, if there is a second letter, get it.
if (grade.length() >= 2) {
  letter2 = grade.substring(1,2);
}

答案 1 :(得分:-2)

在子串(1,2)之前,你应该确保长度> 1。

以下是您想要的。

import java.util.Scanner;

public class Lab6Smalls {

    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);

        String grade;
        double gpa;

        System.out.print("Enter a letter grade: ");

        grade = scan.nextLine();

        if (null == grade || "".equals(grade)) {
            System.out.println("The value is invalid.");
            return;
        }

        switch (grade.substring(0, 1)) {
            case "A":
                gpa = 4.0;
                break;
            case "B":
                gpa = 3.0;
                break;
            case "C":
                gpa = 2.0;
                break;
            case "D":
                gpa = 1.0;
                break;
            case "F":
                gpa = 0.0;
                break;
            default:
                System.out.println("The value is invalid. : " + grade);
                return;
        }

        if (grade.length() > 1) {
            String letter2 = grade.substring(1, 2);
            if ("+".equals(letter2)) {
                gpa += 0.3;
            } else if ("-".equals(letter2)) {
                gpa -= 0.3;
            }
        }

        System.out.println("The numerical value is " + gpa + ".");
    }
}