作业分配要求我使用单个输入字符串并创建4个不同的变量,并允许用户继续输入更多数据。一切正常,但我收到以下错误。
线程“ main”中的异常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)
我有google并搜索了多个线程,但我无法找出任何有帮助的方法。我只是不确定从这里去哪里。
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 "";
}
}
该循环应允许您输入新的输入并再次显示信息。
任何帮助都将非常感谢。
答案 0 :(得分:0)
您的问题在于使用Scanner.nextLine()
和Scanner.nextInt()
。将它们一起使用时应小心,因为它们可能导致意外的行为。您可以阅读Scanner类的JavaDocs以获得更多详细信息。尝试使用newInput = scanner.nextInt()
而不是newInput = Integer.parseInt(scanner.nextLine())
来读取字符串并将其转换为整数。