首页 > 解决方案 > 字符串越界

问题描述

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) 但它显示超出范围

标签: java

解决方案


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);

推荐阅读