Java 读取文件数据时使用子字符串
昨晚我问了一个这样的问题,我不确定发生了什么,我遇到了另一个问题,所以这里是: 我的老师给了我的a班项目一个程序,该程序读取一个文件,读取每个字母,然后打印出每行的点击量、出局量、行走量和牺牲苍蝇量。我在我的博客上发布了更多关于这个话题的信息。 我重写了代码,希望我能有更好的机会让程序正常工作。我了解了什么是子字符串,以及更多关于令牌的知识,并与此程序结合在一起:Java 读取文件数据时使用子字符串,java,Java,昨晚我问了一个这样的问题,我不确定发生了什么,我遇到了另一个问题,所以这里是: 我的老师给了我的a班项目一个程序,该程序读取一个文件,读取每个字母,然后打印出每行的点击量、出局量、行走量和牺牲苍蝇量。我在我的博客上发布了更多关于这个话题的信息。 我重写了代码,希望我能有更好的机会让程序正常工作。我了解了什么是子字符串,以及更多关于令牌的知识,并与此程序结合在一起: import java.util.Scanner; import java.io.*; public class Baseball
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
它指向第25行,这是
String name = input.substring(0,point);
线路。我被难住了,我是不是错过了什么
注:我已经阅读了亚当斯基关于原始问题的建议。我试图遵循它,但由于我是java新手,我很难理解封装,特别是setter和getter方法。我想最好现在就把它们放在一边,直到下一章,我的课程会解释它们。你要处理的是所谓的“边缘条件”。对于你的算法来说,这种情况不是最常见的。但为了避免错误,您还必须处理罕见的情况 您已获得以下代码:
String input = lineScan.nextLine();
int point =(input.indexOf(","));
String name = input.substring(0,point);
这是一个bug诊断的问题(程序员整天都在做这件事。)您现在需要问自己以下几点:
希望这能让你再次前进。你正在处理的被称为“边缘条件”。对于你的算法来说,这种情况不是最常见的。但为了避免错误,您还必须处理罕见的情况 您已获得以下代码:
String input = lineScan.nextLine();
int point =(input.indexOf(","));
String name = input.substring(0,point);
这是一个bug诊断的问题(程序员整天都在做这件事。)您现在需要问自己以下几点:
此
字符串中找不到传入的参数,则返回-1
因此,input
很可能没有在其中找到,
:
int point =(input.indexOf(","));
当您将负索引传入时,将抛出StringIndexOutOfBoundsException
String name = input.substring(0,point); // input.substring(0, -1); will throw the exception
如果在此
字符串中未找到传入的参数,则返回-1
因此,input
很可能没有在其中找到,
:
int point =(input.indexOf(","));
当您将负索引传入时,将抛出StringIndexOutOfBoundsException
String name = input.substring(0,point); // input.substring(0, -1); will throw the exception
请看一行“int point=(input.indexOf(“,”);”当您尝试对“input”进行子串时,请查看“point”解析为什么。请查看行“int point=(input.indexOf(“,”);”当你试图对“输入”进行子串时,看看“点”是什么意思。我想我明白你的意思了。主要问题似乎出现在输入声明上,即读取lineScan的下一个标记。因为lineScan的分隔符是逗号,所以它在字符串中从未看到逗号,因此给出-1。谢谢你给了我需要改进的地方,现在我得想办法把名字印出来。我想我明白你的意思了。主要问题似乎出现在输入声明上,即读取lineScan的下一个标记。因为lineScan的分隔符是逗号,所以它在字符串中从未看到逗号,因此给出-1。谢谢你给了我需要改进的地方,现在我得想办法把名字打印出来。