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) 但它显示超出范围
解决方案
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);
推荐阅读
- laravel - 为什么这个 Laravel 播种机会失败?
- python - 如何修复 virtualenvwrapper_run_hook:12: 和 virtualenvwrapper.sh 问题...?
- rest - Quarkus Resources Not Found 当相同的路径注解位于两个不同的类时
- c++ - std::cout 一次可以输出多少个字符或字符或数据字节?
- asp.net-core - 如何从 asp.net core mvc 中的另一个控制器访问 GET 方法?
- aws-lambda - VPC 中的 Terraform Lambda(与 MongoDB Atlas 对等)连接 NAT 网关
- docker - 来自 RUN apache reload 的 docker-compose up 上存在的 Docker 容器
- android - 如何修改\转换飞镖上的非法字符?
- python - pyodbc.Row object: what are the tuple values
- hittest - 在 Spark AR 的平面跟踪器上点击屏幕底部的测试中心