昨晚我问了这样一个问题,我不确定发生了什么,我遇到了另一个问题,所以这里有:
我的教练给了我的课程一个项目,一个程序读取文件,读取每个字母,然后打印出每个行所有的点击,出局,走路和牺牲苍蝇的数量.我在关于此主题的原始问题中发布了更多信息.我已经重写了代码,我更有机会让程序运行起来.我了解了什么是子串,还有更多关于令牌的知识,并且与这个程序结合在一起:
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
Run Code Online (Sandbox Code Playgroud)
该程序运行正常,但在我输入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)
Run Code Online (Sandbox Code Playgroud)
它指向第25行,即第25行
String name = input.substring(0,point);
Run Code Online (Sandbox Code Playgroud)
线.我对此感到难过,我错过了什么吗?
注意:我已经阅读了Adamski对原始问题的建议.我试图遵循它,但由于我是java的新手,我很难理解封装,特别是setter和getter方法.我认为现在最好不要管它们,直到下一章,我的班级会解释它们.
你所处理的是一种"边缘条件".这种情况不是您的算法最常见的情况.但是你必须处理罕见的情况以避免错误.
你有以下代码:
String input = lineScan.nextLine();
int point =(input.indexOf(","));
String name = input.substring(0,point);
Run Code Online (Sandbox Code Playgroud)
这是一个bug诊断问题(程序员整天都会这样做.)你现在需要问自己以下几点:
希望能让你再次前进.