我正在做一个CSV阅读器,但我得到了一个NullPointerException它说:java.lang.NullPointerException:无法调用“java.util.Scanner.nextLine()”,因为“this.s”在csvReader.(csvReader.java:23)的csvReader.scanner(csvReader.java:34)中为null。
以下是我目前为止的代码:
import java.util.Scanner;
import java.util.NoSuchElementException;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.StringTokenizer;
/**
* Write a description of class csvReader here.
*
* @author (your name)
* @version (a version number or a date)
*/
public class csvReader
{
// instance variables - replace the example below with your own
private int x;
private Scanner s;
private static StringTokenizer tokenizer;
/**
* Constructor for objects of class csvReader
*/
public csvReader()
{
scanner();
}
private static String[] getTokens (String input) {
String[] tokens = new String[5];
// Create empty String in each of 5 locations so
// I can add to them
for (int i = 0; i < tokens.length; i++){
tokens[i] = "";
}
int index = 0; // location in array
int pointer = 0; // location in the String
boolean inQuotes = false; // to keep track of whether the pointer
// within quotes - ignore commas
while (true){
if (pointer == input.length()){
break;
}
if (input.charAt(pointer) == '\"'){
if (inQuotes){
inQuotes = false;
} else {
inQuotes = true;
}
}
else if (input.charAt(pointer) == ','){
if (inQuotes){ // while between quotes
// commas get added at end of current token
tokens[index] += input.charAt(pointer);
} else {
// when not in quotes, comma means move on
// to next token
index++;
}
}
else {
// anything other than " or , will get added to the end
// of my current token.
tokens[index] += input.charAt(pointer);
}
pointer++;
}
return tokens;
}
public void scanner()
{
boolean moreLines = true;
int numTransactions = 0;
while (moreLines)
{
try
{
System.out.println(s.nextLine());
numTransactions++;
}
catch (NoSuchElementException e)
{
moreLines = false;
System.out.println("There are " + numTransactions + "transactions");
}
}
try {
s = new Scanner (new File ("visadata.txt"));
}
catch (FileNotFoundException e)
{
System.out.println("File Not Found");
}
}
}
我做错了什么?
我想让扫描仪告诉我总共有多少笔交易,借记和贷记交易的数量,以及所有借记交易的总数。我现在正忙着查找事务总数,但我得到了一个NullPointerException
1条答案
按热度按时间h5qlskok1#
在
scanner()
函数中,您试图使用类属性s
来读取行。循环将始终开始,因为moreLines
在紧接着之后被设置为true
。您尝试/try
从扫描仪读取行,如果没有行,则尝试catch
(这很好)。但是如果s
还没有初始化,会发生什么呢?当你启动你的程序时,
s
被声明为扫描程序,但它还没有被构建->它是null。尝试在空对象上运行方法会抛出
NullPointerException
,这就是您的问题。在循环之后,您只初始化s
,因此NullPointerException
将至少抛出一次。您需要在程序的前面初始化扫描器(可能在类构造函数中),或者,如果您想保持相同的逻辑,还需要
catch
NullPointerException
s来指示没有要读取的行。这种类型的
Exception
是内置的,所以你不需要import
它。