[英]How to resolve string index out of bounds issue?
家庭作业要求我使用单个输入字符串并创建4个不同的变量,并允许用户继续输入更多数据。 一切正常但我收到以下错误。
线程“main”中的异常java.lang.StringIndexOutOfBoundsException:begin 1,end 0,length 0 at
java.base / java.lang.String.checkBoundsBeginEnd(String.java:3410)位于EmployeeData.main的java.base / java.lang.String.substring(String.java:1883)(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())
读取字符串并将其转换为整数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.