gpt4 book ai didi

java - 在 Java 中将子字符串转换为 Int

转载 作者:行者123 更新时间:2023-12-01 15:06:50 24 4
gpt4 key购买 nike

List<Book> myLibrary = new ArrayList <Book>(312); 
public BookLibrary (Scanner inFile){
while(inFile.hasNextLine()){
String aBook = inFile.nextLine();
String title = aBook.substring(0, 32).trim();
String language = aMovie.substring(33, 40).trim();
String rating = aMovie.substring(41, 50).trim();
int hardCover = Integer.parseInt(aBook.substring(51, 55).trim());
int paperBack = Integer.parseInt(aBook.substring(56));
myLibrary.add(new Book (title, language, rating,
hardCover, paperBack));
count++;
}

这里只是一些示例代码。我试图找出为什么当我尝试运行我的程序时收到此运行时错误。我的程序中没有编译器错误。

Exception in thread "main" java.lang.NumberFormatException: For input string: ""
at java.lang.NumberFormatException.forInputString(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
at MovieCollection.<init>(BookLibrary.java:21)

最佳答案

文件格式有错误(缺少某些值)或索引有错误(子字符串方法的参数),请将此方法调用纠正为适当的:

substring(51, 55)
substring(56)

现在其中一个返回空字符串。

如果hardCower或papperBack可以为空,则使用try/catch构造:

int hardCover = 0;
int paperBack = 0;
try{
hardCover = Integer.parseInt(aBook.substring(51, 55).trim());
}catch(NumberFormatException nfe){}

try{
paperBack = Integer.parseInt(aBook.substring(56));
}catch(NumberFormatException nfe){}

或进行检查

String toInt1 = aBook.substring(51, 55).trim();
if(toInt1.length > 0){
hardCover = Integer.parseInt(toInt1);
}

关于java - 在 Java 中将子字符串转换为 Int,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12852621/

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