0
我在我的代码的第59行出现NullPointerException时出现问题。Java - 获取NullPointerException
该程序的目的是提示用户文件位置(其中有数字的PI)。然后程序应该通过Scanner类接受任意数量的数字(比如说k个数字)。然后,程序必须从文件中读取PI的k个数字。使用Scanner类,程序应该从用户那里获得一个0-9的数字,并打印它出现的第一个和最后一个位置,以及它出现的次数。只考虑小数点后的数字。该程序应该能够接受100,000位数的PI。
代码的样本输出低于:
Give the location of the file:
C:\Users\Joe\Desktop\pi.txt
Number of digits of PI to parse:
10
Give any number between 0-9:
1
1 appears 2 times
First position in which appears: 1
Last position in which appears: 3
任何帮助,将不胜感激。
下面是我的代码:
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.Scanner;
import java.util.ArrayList;
public class Problem2 {
@SuppressWarnings("null")
public static void main(String[] args) throws Exception {
FileInputStream inputstream = null;
BufferedReader reader = null;
@SuppressWarnings("resource")
Scanner input = new Scanner(System.in);
try {
System.out.println("Give the location of the file (example: C:\\Users\\Joe\\Desktop\\pi.txt):");
String fileloc = input.nextLine();
inputstream = new FileInputStream(fileloc);
reader = new BufferedReader(new InputStreamReader(inputstream));
String stringinput;
System.out.println("Number of digits of PI to parse: ");
int parsenum = input.nextInt() + 2;
String[] stringarray = new String[parsenum];
while((stringinput = reader.readLine()) != null) {
stringinput = stringinput.substring(2, parsenum);
for(int i = 0; i < stringinput.length(); i++) {
stringarray = stringinput.split("");
}
}
System.out.println("Give any number between 0-9: ");
String searchnum = input.next();
int count = 0;
for(int i = 1; i < parsenum - 1; i++) {
if(searchnum == stringarray[i]) {
count++;
}
else count++;
}
System.out.println(searchnum + " appears " + count + " time(s)");
for(int i = 1; i < parsenum - 1; i++) {
System.out.print(stringarray[i]);
}
System.out.println();
System.out.println("First position in which " + searchnum + " appears: " + stringinput.indexOf(searchnum));
System.out.println("Second position in which " + searchnum + " appears: " + stringinput.lastIndexOf(searchnum));
}
catch (FileNotFoundException exception) {
System.err.println("File not found, please try again");
main(null);
}
catch (Exception e) {
System.err.println("Invalid input entered");
e.printStackTrace();
System.exit(0);
}
finally {
reader.close();
}
}
}
而59行将是...? – MadProgrammer
作为一般经验法则,如果你打开它,你应该关闭它。有关更多详细信息,请参见[try-with-resources语句](https://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html) – MadProgrammer
请阅读http://stackoverflow.com/questions/218384/what-is-null-pointer-exception-and-how-do-i-fix-it - 这会让你更好地了解如何追踪和解决这些问题。 (这通常是*不是很好的问题;每一个都是由于对程序状态的错误假设而导致的编程错误。) – user2864740