gpt4 book ai didi

java - 读取文件数据时使用子字符串

转载 作者:行者123 更新时间:2023-11-29 03:52:58 24 4
gpt4 key购买 nike

昨晚我问了这样一个问题,我不确定发生了什么,我遇到了另一个问题所以这里是:

我的老师给了我的类(class)一个项目,一个读取文件的程序,读取每个字母,然后打印出每行的命中数、出局数、保送数和牺牲果蝇数。我在我的 original question 中发布了更多信息关于这个话题。我已经重写了代码,以便更好地让程序运行。我了解了什么是子字符串以及更多关于标记的知识,并与这个程序结合在一起:

import java.util.Scanner;
import java.io.*;

public class BaseballStats
{
public static void main(String[]args) throws IOException
{
Scanner fileScan, lineScan;
String fileName;
int oCount = 0, hCount = 0, sCount = 0, wCount = 0;
Scanner scan = new Scanner(System.in);

System.out.print("Enter the name of the input file: ");
fileName = scan.nextLine();
fileScan = new Scanner(new File(fileName));

while (fileScan.hasNext())
{
lineScan = new Scanner (fileName);
lineScan.useDelimiter(",");

String input = lineScan.nextLine();
int point =(input.indexOf(","));

String name = input.substring(0,point);
String records = input.substring(point,input.length());

for (int i = 0; i < records.length(); i++)
{
if (records.charAt(i) == 's')
sCount++;
else if (records.charAt(i) == 'o')
oCount++;
else if (records.charAt(i) == 'h')
hCount++;
else if (records.charAt(i) == 'w')
wCount++;
}// end of for loop
System.out.printf("Name: %s. Hits: %d. Outs: %d. Walks: %d. Sacrifice flies: %d.", name, hCount, oCount, wCount, sCount);
System.out.println();

}//end of while loop

}//end of main
}// end

程序运行正常,但在我输入stats.dat(应该读取的文件)后,出现以下异常错误:

java.lang.StringIndexOutOfBoundsException: String index out of range: -1
at java.lang.String.substring(Unknown Source)
at BaseballStats.main(BaseballStats.java:25)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at edu.rice.cs.drjava.model.compiler.JavacCompiler.runCommand(JavacCompiler.java:271)

它指向第25行,也就是

String name = input.substring(0,point);

行。我对此感到困惑,我是否遗漏了什么?

注意:我已经阅读了 Adamski 对原始问题的建议。我试图遵循它,但由于我是 java 的新手,我很难理解封装,特别是 setter 和 getter 方法。我认为在下一章之前最好暂时不要管它们,我的类(class)会在下一章解释它们。

最佳答案

您正在处理的称为“边缘条件”。这种情况不是您的算法最常见的情况。但是您还必须处理罕见的情况以避免错误。

您有以下代码:

String input = lineScan.nextLine();
int point =(input.indexOf(","));
String name = input.substring(0,point);

这是一个错误诊断的问题(程序员整天都在做。)你现在需要问自己以下问题:

  1. “StringIndexOutOfBoundsException”是什么意思?谷歌会告诉你的。
  2. 这怎么可能?调用子字符串时会导致该错误的原因是什么? (Google java substring 以查看导致 substring 抛出该异常的原因。)
  3. 这会让您查看 indexOf() 方法(同样,google 是您的 friend ),以及从中返回什么样的结果可能会导致堆栈跟踪。
  4. 什么样的输入会导致那种情况?

希望这能让你再次前进。

关于java - 读取文件数据时使用子字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7841860/

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