字符串越界

时间:2019-01-02 15:27:18

标签: java

import java.io.*;
import java.util.*;
class Decision
{

        public static void main(String[] args)
        {

            String name[] = new String[75];
            double basic[] = new double[75];
            char grade[] = new char[75];
            double net[] = new double[75];
            int i;
            Scanner sc = new Scanner(System.in);
            for(i=0;i<75;i++)
            {
                System.out.println("Enter the name , basic salary and grade(A/B/C)of the employee");
                name[i]=sc.nextLine();
                basic[i]=sc.nextDouble();
                grade[i]=sc.nextLine().charAt(0);
                if(grade[i]!='A'||grade[i]!='a'||grade[i]!='B'||grade[i]!='b'||grade[i]!='C'||grade[i]!='c')
                    {
                        System.out.println("Grade must be A/B/C, Please re-enter again");
                        i--;
                    }
            }
        double da,hra,ma,it,bs;
        char c;
            System.out.println("Name\tBasic\tDA\tHRA\tMA\tIT\tNetSalary");
            for(i=0;i<75;i++)
            {
                c=grade[i];

我遇到错误grade [i] = sc.nextLine(),甚至我尝试了grade [i] = sc.nextLine()。charAt(0),但显示超出范围

1 个答案:

答案 0 :(得分:0)

sc.nextDouble()

在双精度后不使用换行符。这意味着,当您之后调用sc.nextLine()时,您会得到双精度字符和换行符之间的所有内容-这是一个空字符串-因此sc.nextLine().charAt(0)会产生StringIndexOutOfBoundsException

随后添加一个nextLine()呼叫:

        basic[i]=sc.nextDouble();
        sc.nextLine();  // This
        grade[i]=sc.nextLine().charAt(0);

或者,将double读取为字符串,然后自己解析:

        basic[i]=Double.parseDouble(sc.nextLine());
        grade[i]=sc.nextLine().charAt(0);