Java NullPointerException when using scanner.hasNext(); - java

I came up with the following code to read information from a file:
import java.io.*;
import java.util.*;
public class Reader {
private Scanner s;
public void openFile() {
try {
s = new Scanner(new File("file.txt"));
} catch (Exception e) {
System.out.println("File not found. Try again.");
}
}
public void readFile() {
while (s.hasNext()) {
String a = s.next();
String b = s.next();
String c = s.next();
int d = s.nextInt();
int e = s.nextInt();
int f = s.nextInt();
}
public void closeFile() {
s.close();
}
}
However, I get a NullPointer error on the (while (s.hasNext())) line and can't find a solution.
I'm working in Eclipse and the file I'm reading from is imported correctly into the project so that should not be an issue.
EDIT:
The way I access the methods:
public class Tester {
public static void main(String[] args) {
Reader read = new Reader();
read.openFile();
read.readFile();
read.closeFile();
}
}

As per the statement where NPE throws, while (s.hasNext()), it's most probable that the s is null pointer, you can add System.out.println(s); before that statement to double confirm it.
And for the reason why the s is null, there are two possible reasons:
You didn't invoke openFile before readFile
Exception is thrown when you open the file. The s is only a declaration and hasn't pointed to any object yet.
Maybe for a better practice, you can assert whether a instance is null or not before invoking its method. And as per my understanding, the readFile depends on the result of openFile, maybe you can set return value of openFile like a boolean value and check the return value before further open file operation. It's impossible to read a file which can't be even open, right?
import java.io.*;
import java.util.*;
public class Reader {
private Scanner s;
public boolean openFile() {
try {
s = new Scanner(new File("file.txt"));
return true;
} catch (Exception e) {
System.out.println("File not found. Try again.");
return false;
}
}
public void readFile() {
while (s.hasNext()) {
String a = s.next();
String b = s.next();
String c = s.next();
int d = s.nextInt();
int e = s.nextInt();
int f = s.nextInt();
}
}
The invoker can do something like below:
Reader reader = new Reader();
if (reader.openFile())
reader.readFile();

Related

Scanner class NoSuchElement Errors

Stacktrace
Can't figure out why I'm receiving NoSuchElement errors as the build works perfectly on my PC but my Mac doesn't.
Not sure if it's an error with my code - referring to the issue where the Scanner is trying to read a line that doesn't exist. But surely it can't be as my PC runs it perfectly.
package equipment;
import java.util.*;
import java.io.*;
public class Equipment
{
public static void main(String[] args)
{
String line;
String description;
int quantity;
double value;
try
{
Scanner scFile = new Scanner (new File("Stock.txt"));
System.out.println("Product\tQuantity\tPrice");
System.out.println("-------\t--------\t------");
while (scFile.hasNext())
{
line = scFile.nextLine();
Scanner scTokens = new Scanner(line).useDelimiter("&");
description = scTokens.next();
quantity = scTokens.nextInt();
value = scTokens.nextDouble();
System.out.println(description + quantity + value);
}
scFile.close();
}
catch (FileNotFoundException f)
{
System.out.println("Error - File Not Found");
}
}
}

Creating, writing to and reading files

I know there are many questions related to this, but I still do not follow. I have copied the below code from a tutorial on how to create, write to and read from a file. There is a CreateFile class, a ReadFile class and a Demo class:
CreateFile.java
import java.io.*;
import java.lang.*;
import java.util.*;
public class CreateFile {
private Formatter x;
public void openFile(){
try{
x = new Formatter("chinese.txt");
}
catch(Exception e)
{
System.out.println("You have an error");
}
}
public void addRecords(){
x .format("%s%s%s", "20 ", "bucky ", "robers");
}
public void closeFile(){
x.close();
}
}
ReadFile.java
public class ReadFile {
private Scanner x;
public void openFile()
{
try{
x = new Scanner(new File("words.txt"));
}
catch(Exception e){
System.out.println("could not find file");
}
}
public void readFile()
{
while(x.hasNext())
{
String a = x.next();
String b = x.next();
String c = x.next();
System.out.printf("%s %s %s\n", a,b,c);
}
}
public void closeFile()
{
x.close();
}
}
public class Demo {
public static void main(String[] args) {
CreateFile g = new CreateFile();
g.openFile();
g.addRecords();
g.closeFile();
WordCounter r = new WordCounter();
r.openFile();
r.readFile();
r.closeFile();
}
In Demo.java if I remove the last four statements related to reading the file, the first four statements related to opening and writing to a file run without error. However, once I add
WordCounter r = new WordCounter();
r.openFile();
r.readFile();
r.closeFile();
and run the program, it outputs: Exception in thread "main" could not find file. I am not sure what is going on, is the file chinese.txt never being created?
I'd suggest that you look into serialization it much easier and simpler than writing to .txt files.
But if you really need to do .txt files this is how you write to a .txt file
//This gets your project directory
private String projectPath = System.getProperty("user.dir");
//call save()
String save("test.txt", "This is will be save to a test.txt file");
private boolean save(String textfile String outputtext){
String filepath = projectPath + textfile;
try{
BufferedWriter writer = new BufferedWriter(new FileWriter(filepath));
writer.write(outputtext);
writer.close();
} catch(IOException e) { }
return true;
}
And this is how you read it
private String load(String textfile){
String temp="";
String filepath = projectPath + textfile;
try{
BufferedReader reader =new BufferedReader(new FileReader(filepath));
while(true){
//this will read one line at a time you can append it output
try {
temp+= reader.readLine();
//If no more lines break out of the loop
if(line==null)
break;
}catch(IOException e){}
}
reader.close();
}
catch(IOException e){}
//Return contents of the file you loaded
return temp;
}
I hope that this code is clear enough. If you have any further questions let me know. I'll gladly answer them.

CODECHEF: Runtime Error (NZEC)

I attempted a problem from codechef and made my code on java which runs perfectly on eclipse on my laptop.But everytime i try to submit the code it gives me this NZEC error.
Can anyone tell why am i getting the non zero exit code error (NZEC) while i am executing this code.
Problem to this code: https://www.codechef.com/problems/STRPALIN
import java.util.*;
import java.io.*;
public class Palindrome {
public boolean check() throws IOException{
String A;
String B;
BufferedReader inp = new BufferedReader (new InputStreamReader(System.in));
A=inp.readLine();
B=inp.readLine();
for(int i=0;i<A.length();i++)
{
for(int j=0;j<B.length();j++)
{
if(A.charAt(i)==B.charAt(j))
return true;
}
}
return false;
}
public static void main(String[] args)throws NumberFormatException, IOException {
Palindrome M = new Palindrome();
boolean[] array = new boolean[10];
BufferedReader in = new BufferedReader (new InputStreamReader(System.in));
int T = Integer.parseInt(in.readLine());
for(int i=0;i<T;i++)
{
array[i]=M.check();
}
for(int j=0;j<T;j++){
if(array[j])
System.out.println("Yes");
else
System.out.println("No");
}
}
}
The problem with your code is that while taking input from user for String A and B, the readline() method returns null, and when you try to access String A or B, a NullPointerException is thrown. Hence the non-zero exit code .
Now, the readline() method returned null value because you created a BufferedReader object twice, which led to leakage of memory.
Refer to this link: readline() returns null in Java
Regarding the NZEC error:
import java.util.*;
import java.io.*;
class Codechef {
public boolean check() throws IOException{
String A;
String B;
BufferedReader inp = new BufferedReader (new InputStreamReader(System.in));
A=inp.readLine();
B=inp.readLine();
for(int i=0;i<A.length();i++)
{
for(int j=0;j<B.length();j++)
{
if(A.charAt(i)==B.charAt(j))
return true;
}
}
return false;
}
public static void main(String[] args)throws NumberFormatException, IOException {
try {
Codechef M = new Codechef();
boolean[] array = new boolean[10];
BufferedReader in = new BufferedReader (new InputStreamReader(System.in));
int T = Integer.parseInt(in.readLine());
for(int i=0;i<T;i++)
{
array[i]=M.check();
}
for(int j=0;j<T;j++){
if(array[j])
System.out.println("Yes");
else
System.out.println("No");
}
} catch(Exception e) {
} finally {
}
}
}

Reading a .txt file that results in a stackoverflow error

Can someone please help me determine what I am doing wrong with my code. I am getting a stackoverflow error. At the end of my code I am using recursion and I don't have a base case to stop the program. It keeps looping and displaying my text file until I get a stackoverflow error.
public class Reader
{
public static String readFinalQuestionBank() throws Exception
{
File textFile = new File("C:\\Users\\Joseph\\Documents\\School Files - NHCC\\CSci 2002\\FinalQuestionBank_JosephKraemer.txt"); //file location
try
{
Scanner scan = new Scanner(textFile); //Scanner to import file
while(scan.hasNextLine()) //Iterator - while file has next line
{
String qBank = scan.nextLine(); //Iterator next line
String[] tempArray = qBank.split("::"); //split data via double colon
System.out.println(qBank); //print data line
}
scan.close(); //close scanner
}
catch(FileNotFoundException e)
{
e.printStackTrace();
}
return readFinalQuestionBank(); //use of Recursion
}//end method readFinalQuestionBank
}//end class Reader
if your main objective is to read the whole input file by implementing recursivity take a look at the following example, it replaces the while statement with a recursive method call.
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class Reader
{
public static String readFinalQuestionBank() throws Exception
{
File textFile = new File("C:\\Users\\Diego\\Documents\\sandbox\\input.txt");
String output = "";
try
{
Scanner scan = new Scanner(textFile);
output = readLineRecursively(scan);
scan.close();
}
catch(FileNotFoundException e)
{
e.printStackTrace();
}
return output;
}
private static String readLineRecursively(Scanner scan){
if(!scan.hasNextLine()){
return "";
}
String qBank = scan.nextLine();
return qBank + "\n" + readLineRecursively(scan);
}
public static void main(String[] args){
try {
System.out.println(readFinalQuestionBank());
} catch (Exception e) {
e.printStackTrace();
}
}
}

Java: Make a void-method out of this class (textfile changer)

What I want to do: My class copytest reads a textfile, edits one character and save this new file in a new directory. I want to program a void-method out of it, which does exactly the same and can then be used the following way:
copy(String "C:\\Old.txt", String "C:\\New.txt", int 1, int 1)
Now copy does exactly the same as my old class copytest, it reads the old file, edits it and saves it.
My first idea was to have two files as the first to arguments, but this is obviously impossible. My new idea is to give the method two strings of the wanted directories of the old and the new file. It still doesn't work. I hope, you understand, what I want to do and how to solve this problem.
Old class code (works):
import java.io.*;
import java.util.Scanner;
public class copytest {
public static void main(String[] args) throws Exception {
readFile();
}
public static void readFile() throws Exception {
// Location of file to read
File file = new File("...old.txt");
Scanner scanner = new Scanner(file);
int lineNumber=1;
int charNumber=1;
String wantedChar="r";
int i=0;
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
if (i == lineNumber+2) {
if (line.length() >= charNumber) {
line = line.substring(0,charNumber-1) + wantedChar + line.substring(charNumber);
}
}
writeFile(line);
i++;
}
scanner.close();
System.out.println("File copied.");
}
public static void writeFile(String copyText) throws Exception {
String newLine = System.getProperty("line.separator");
// Location of file to output
Writer output = null;
File file = new File("...new.txt");
output = new BufferedWriter(new FileWriter(file, true));
output.write(copyText);
output.write(newLine);
output.close();
}
}
New void code (first try with file as argument):
public void copy(file old, file new, int x, int y) {
public static void readFile() throws Exception {
Scanner scanner = new Scanner(old);
int lineNumber=y;
int charNumber=x;
String wantedChar="r";
int i=0;
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
if (i == lineNumber+2) {
if (line.length() >= charNumber) {
line = line.substring(0,charNumber-1) + wantedChar + line.substring(charNumber);
}
}
writeFile(line);
i++;
}
scanner.close();
System.out.println("File copied.");
}
public static void writeFile(String copyText) throws Exception {
String newLine = System.getProperty("line.separator");
// Location of file to output
Writer output = null;
File file = new File(new.getPath());
output = new BufferedWriter(new FileWriter(file, true));
output.write(copyText);
output.write(newLine);
output.close();
}
readFile();
}
New try with strings as argument, but still doesn't work:
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.Writer;
import java.util.Scanner;
public class copytestnew {
public void copy(String old, String newone, int x, int y) {
// Location of file to read
File file = new File(old);
Scanner scanner = new Scanner(file);
int lineNumber=y;
int charNumber=x;
String wantedChar="r";
int i=0;
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
if (i == lineNumber+2) {
if (line.length() >= charNumber) {
line = line.substring(0,charNumber-1) + wantedChar + line.substring(charNumber);
}
}
String newLine = System.getProperty("line.separator");
// Location of file to output
Writer output = null;
File file2 = new File(newone);
output = new BufferedWriter(new FileWriter(file2, true));
output.write(line);
output.write(newLine);
output.close();
i++;
}
scanner.close();
System.out.println("File copied");
}
}
I remember you! I answeared you last time on how to replace the char at one of the lines.
First, change the decleration to
public static void copy(String old, String newone, int x, int y) throws IOException {
NOTICE the throws statment!
And now when you want to call this method you should use it inside a try-catch block or declear that you throwing exception same as you did at the copy function.
public void copy(file old, file new, int x, int y) {
public static void readFile() throws Exception {
You're defining a function inside a method. As all functions in java are methods (static or non-static), this is not permitted. Try this:
class IDontKnowHowToNameIt {
public static void copy(file old, file new, int x, int y) {
//...
// call readFile from here
// ...
}
private static void readFile() throws Exception {
//...
}
}

Categories

Resources