gpt4 book ai didi

java - 如何解决字符串索引超出范围的问题?

转载 作者:行者123 更新时间:2023-12-02 05:20:24 26 4
gpt4 key购买 nike

作业分配要求我使用单个输入字符串并创建4个不同的变量,并允许用户继续输入更多数据。一切正常,但我收到以下错误。


线程“主”中的异常java.lang.StringIndexOutOfBoundsException:开始于1,结束于0,长度为0,位于
java.base / java.lang.String.checkBoundsBeginEnd(String.java:3410)
在java.base / java.lang.String.substring(String.java:1883)
在EmployeeData.main(EmployeeData.java:24)


我有谷歌,并搜索几个线程,我不知道有什么会有所帮助。我只是不确定从这里要去哪里。

import java.util.Scanner; 

public class EmployeeData
{

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

String custInp;
String fName = "";
String lName = "";
int empID;
double wage;
//initation loop
int newInput=1;
while(newInput==1)
{
//input in single string
System.out.println("Please enter First name, last name, emp ID
and wage. (include space inbetween each)");
custInp = scanner.nextLine();
//cut string into variables
fName = splitNext(custInp, ' ');
custInp = custInp.substring(fName.length() + 1,
custInp.length());
lName = splitNext(custInp, ' ');
custInp = custInp.substring(lName.length() + 1,
custInp.length());
String temp = splitNext(custInp, ' ');
empID = Integer.parseInt(temp);
custInp = custInp.substring(custInp.indexOf(' ') + 1,
custInp.length());
wage = Double.parseDouble(custInp);
//set data
Employee emp = new Employee(fName, lName, empID, wage);
//get data
System.out.println(fName + " " + lName + " " + empID + " " +
wage);
System.out.println("Employee Name: " + emp.getFirstName() + "
" + emp.getLastName());
System.out.println("Employee ID: " + emp.getEmpID());
System.out.println("Employee Wage: " + emp.getWage());
System.out.println("");
//decide to continue or not
System.out.println("Do you want to add more? 1=Yes or 2=no");
newInput = scanner.nextInt();
//THIS IS WHERE the issue happens
}
}


public static String splitNext(String s, char delim)
{
//location of first space character in s
int delimIndex = s.indexOf(delim);

//require that next is at least 1 char long
if(delimIndex > 0)
{
//set next to all chars in s preceding first space found
String next = s.substring(0, delimIndex);

//truncate beginning of s so that s.find(' ') can reach second
s = s.substring(delimIndex + 1, s.length());

return next;
}

return "";
}
}


该循环应允许您输入新的输入并再次显示信息。

任何帮助将非常感谢。

最佳答案

您的问题是使用Scanner.nextLine()Scanner.nextInt()。将它们一起使用时应小心,因为它们可能导致意外的行为。您可以阅读Scanner类的JavaDocs以获得更多详细信息。尝试使用newInput = scanner.nextInt()而不是newInput = Integer.parseInt(scanner.nextLine())读取字符串并将其转换为整数。

关于java - 如何解决字符串索引超出范围的问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56267245/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com