Java - Getting NullPointerException [duplicate] - java

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 7 years ago.
I have a problem with where I am getting a NullPointerException on line 59 of my code.
The program's purpose is to prompt the user for the file location (which has the digits of PI). The program should then accept any number of digits (say k digits) via the Scanner class. Then, the program must read k digits of PI from the file. Using the Scanner class, the program should then obtain a number for 0-9 from a user and print the first and last position in which it appears and also the number of times it appears. Only digits after the decimal point are to be considered. The program should be able to accept 100,000 digits of PI.
The sample output of the code is below:
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
Any help would be much appreciated.
Below is my code:
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();
}
}
}

while((stringinput = reader.readLine()) != null)
The above while loop will run untill reader.readLine is null and so will be stringinput.
Now after the while loop your using stringinput:
stringinput.indexOf(searchnum)
stringinput.lastIndexOf(searchnum)
and thus getting the NullPointerException.

Related

How would I edit a specific line in a text file with java?

I am writing a program that lets the user enter up to 9999 accounts into a text file, however the issue i'm having is that they can be put in any order, but I have to print them in a sequential order. Here's my code
import java.nio.file.*;
import java.io.*;
import java.nio.channels.FileChannel;
import java.nio.ByteBuffer;
import static java.nio.file.StandardOpenOption.*;
import java.util.Scanner;
import java.text.*;
public class CreateBankFile {
public static int lines = 0;
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
Path file = Paths.get("/root/sandbox/BankAccounts.txt");
String line = "";
int acctNum = 0;
String lastName;
double bal;
final int QUIT = 9999;
try
{
OutputStream output = new BufferedOutputStream(Files.newOutputStream(file));
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(output));
while(acctNum != QUIT)
{
System.out.print("Enter the acct num less than 9999: ");
acctNum = input.nextInt();
if(acctNum == QUIT)
{
continue;
}
System.out.print("Enter a last name: ");
lastName = input.next();
if(lastName.length() != 8)
{
if(lastName.length() > 8)
{
lastName = lastName.substring(0, 8);
}
else if(lastName.length() < 8)
{
int diff = 8 - lastName.length();
for(int i = 0; i < diff; i++)
{
lastName += " ";
}
}
}
System.out.print("Enter balance: ");
bal = input.nextDouble();
line = "ID#" + acctNum + " " + lastName + "$" + bal;
writer.write(line);
writer.newLine();
lines++;
}
writer.close();
}
catch(IOException e)
{
System.out.println("Error");
}
}
}
My question being, how can I get it so that when the user inputs "55" for example, it is printed to the 55th line of the text file?
You can do something like this :
1) create a class that will store your line ( acctNum , lastName .. etc )
2) in your method , create an arraylist of the class you created , for a given number "n" , your method will parse all the lines , if acctNum is less than "n" , you will create a new instance using this line and add it to your arraylist
3) you will sort the arraylist using the acctNum and then print its content
Perhaps FileChannels would work for you:
RandomAccessFile writer = new RandomAccessFile(file, "rw");
FileChannel channel = writer.getChannel();
ByteBuffer buff = ByteBuffer.wrap("Test write".getBytes(StandardCharsets.UTF_8));
channel.write(buff,5);//5 is the distance in the file
Lots of good examples on the web.
In your question I think you are taking acctNum as line number and you want to add a line at this line number in the file so you can do something like this.
List<String> readLines = Files.readAllLines(path, StandardCharsets.UTF_8);
readLines.set(acctNum- 1, data);
Files.write(path, lines, StandardCharsets.UTF_8);
I assumed that you are using Java 7 or higher so I did acctNum-1 because in Java 7 or higher version line number starts with 1 in rest it starts with 0 so you can change to acctNum.
Reference: List set() and NIO

How to scan the amount of integers within an ArrayList index

I'm trying to make a program that checks an ArrayList and makes sure that each index includes only 2 integers per line, and doesn't include any doubles or strings.
If the arraylist is:
0 1
2 34
32 51 32
it would pull up an error message for the third line for having 3 integers. The program needs to check that it has only two integers per line, is only 12 lines long, and doesn't include any doubles or strings. This is what I have so far:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
import java.util.ArrayList;
public class TextFileReader {
public static void main(String[] args) {
int fileCount = 0;
ArrayList<String> inputFile = new ArrayList<String>(20);
try (Scanner fileScanner = new Scanner(new File("perfect_file.txt"))) {
while (fileScanner.hasNext()) {
inputFile.add(fileScanner.nextLine());
}
} catch (FileNotFoundException e) {
System.out.println("Error reading generic answers, program ending.");
System.exit(1);
}
if (inputFile.size() > 12) {
System.out.println("Error: Lines exceed 12");
}
if (inputFile.size() < 12) {
System.out.println("Error: Not enough lines");
}
}
}
I would really appreciate any help on this. Thank you!
Use String split, it's look like
try (Scanner fileScanner = new Scanner(new File("perfect_file.txt"));) {
while (fileScanner.hasNextLine()) {
String[] line = fileScanner.nextLine().split("\\s+");
if (line.length == 2) {
// Ok, do something
// System.out.println("First: " + line[0] + ", Second: " + line[1]);
} else {
// Wrong
System.out.println("The number of line " + line.length);
}
}
}

reading and printing from txt file integers java [duplicate]

This question already has answers here:
What is character encoding and why should I bother with it
(4 answers)
Closed 4 years ago.
I wrote the below code in order to read some integers from a text file and then print in a new txt every integer after I added the value ten to each of them. The "-1" int is as a pointer to show the end.
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.PrintWriter;
import java.util.Scanner;
public class SmallChallengeCh {
public static void main(String[] args){
Scanner in = null;
PrintWriter pw = null;
try{
File f = new File("C:\\Users\\paioa\\primlnl.txt");
in = new Scanner(f);
pw = new PrintWriter(new FileOutputStream("C:\\Users\\paioa\\primOut.txt"),true);
int num = in.nextInt();
while(num != -1 ){
num = num + 10;
System.out.print(num + " ");
pw.print(num + " ");
num = in.nextInt();
}
}catch(FileNotFoundException e1){
System.out.println("The file does not exist");
}finally {
try{
if(in != null) in.close(); else throw new Exception("NULL");
if(pw != null) pw.close();else throw new Exception("NULL");
}catch (Exception e){
System.out.println(e.getMessage());
}
}
}
}
However I am getting the below error
**Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Scanner.java:864)
at java.util.Scanner.next(Scanner.java:1485)
at java.util.Scanner.nextInt(Scanner.java:2117)
at java.util.Scanner.nextInt(Scanner.java:2076)
at gr.aueb.elearn.ch6.SmallChallengeCh.main(SmallChallengeCh.java:18)
Process finished with exit code 1**
But I cannot understand why. The inputmismatchexception is due to the fact that probably my file doesn't contain ints but that's not true here is the txt.
Input of txt file, also saved with coding UTF-8
Solved
ANSWER: The issue was with coding UTF-8. I should left the file ANSI. I don't know why the example I was reading/exercising on advocated this ..
try this
int num;
while(in.hasNextInt()){
num = in.nextInt();
num = num + 10;
System.out.print(num + " ");
pw.print(num + " ");
}
If you want to read only integers before "-1" you have to do something like
int num;
while(in.hasNextInt()){
num = in.nextInt();
if(num == -1)
break;
num = num + 10;
System.out.print(num + " ");
pw.print(num + " ");
}

Error while reading the last entry of a file

I am reading a file using a delimiter with a scanner. When I get to the last entry of the file it says I am out of bounds. If I count correctly I am in bounds though.
Here is the code and it is throwing an input mismatch error. Any help is appreciated. Thanks.
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.InputMismatchException;
import java.util.NoSuchElementException;
import java.util.Scanner;
public class Test {
public static void main(String[] args) throws IOException {
String personName = null;
double score = 0;
File myFile = new File("twogrades.dat");
try {
Scanner scan = new Scanner(myFile).useDelimiter(",");
while (scan.hasNext()) {
personName = scan.next();
for (int i = 0; i <= 5; i++) {
score += ((scan.nextDouble() / 50) * 0.03);
}
for (int i = 6; i <= 11; i++) {
score += ((scan.nextDouble() / 10) * 0.02);
}
score += ((scan.nextDouble()) * 0.20);
score += ((scan.nextDouble()) * 0.50);
PrintWriter out = new PrintWriter(new BufferedWriter(
new FileWriter("grades.dat", true)));
out.println(personName + " " + score);
out.close();
score = 0;
scan.nextLine();
}
scan.close();
} catch (InputMismatchException e) {
System.out.println(e.getMessage()
+ " You entered a wrong data type");
} catch (NoSuchElementException e) {
System.out.println(e.getMessage()
+ " There are no more elements left in the file");
} catch (IllegalStateException e) {
System.out.println(e.getMessage());
}
}
}
Here is the file
Yuri Allen,5,26,16,22,18,3,0,4,4,2,10,2,54,89
I am able to reproduce the error, but only if there is more than one line in the input file. The problem is the delimiter. You only use the comma ",". Thus, the scanner tries to read the new line character with the last entry of the line: "89\n". Since this is not a valid double, you get the exception.
You can solve this by adding the new line character as a delimiter: ",|\\r\\n|\\r|\\n"
I run it and the result is: No line found There are no more elements left in the file and the output Yuri Allen 55.398. Possibly you can clean, rebuild your project and change:
while (scan.hasNext()) {
to this
while (scan.hasNextLine()) {

Average of numbers in a .txt file using a scanner

I am currently trying to create a Java program that allows a scanner to read 100 integers from a .txt file and then for the program to output the average of the 100 numbers. It must also check for errors whilst reading from the code. E.G (there is a letter in .txt file, instead of an integer).
Here is the code I have so far:
package NumFile;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.text.DecimalFormat;
import java.util.Scanner;
public class NumFile {
public static void main (String [] args) throws FileNotFoundException {
try {
int counter = 0; // Counter for number of numbers in the txt file
double sum = 0; // Sum of all digits in the txt file
String line = null; // The line that is read in the txt file
Scanner userIn = new Scanner(System.in);
System.out.println("Type the name of the file located");
String fileName = userIn.nextLine();
BufferedReader in = new BufferedReader(new FileReader(Workbook1.txt));
Object input;
while(in.hasNextLine() && !((input = in.nextLine()).equals(""))) {
counter++;
sum += Double.parseDouble(line);
}
double average = sum/counter;
System.out.println("The average of the numbers is: " + format(average));
System.out.println("The sum of the numbers is: " + sum);
System.out.println("The number of digits is " + counter);
}
catch (IOException e) {
System.out.println("Input/Output exception");
}
}
public static String format(double number) {
DecimalFormat d = new DecimalFormat("0.00");
return d.format(number);
}
}
With this code, I am having a few errors.
Here are the errors that display:
Exception in thread "main" java.lang.Error: Unresolved compilation problems:
Workbook1 cannot be resolved to a variable
The method hasNextLine() is undefined for the type BufferedReader
The method nextLine() is undefined for the type BufferedReader
at NumFile.NumFile.main(NumFile.java:27)
If I remove:
Object input;
// Loop until the end of the file
while(in.hasNextLine() && !((input = in.nextLine()).equals(""))){
then the program starts to run, however it cannot find the .txt file containing the integers!
You can do something like this:
Scanner in = new Scanner(new File(fileName));
String input = "";
while(in.hasNextLine() && !((input = in.nextLine()).equals(""))) {
//code here
}

Categories

Resources