Scanner class NoSuchElement Errors - java

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");
}
}
}

Related

Java NullPointerException when using scanner.hasNext();

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();

Search and update a string in a text file in JAVA

I have two text files namely - item.txt (file 1) and temp.txt (file 2). My goal is to search for a name in the file 1 and if found then replace it with a different name and write the updated line to file 2. Also, I have a method that checks for the lines for the string I searched in file 1. The lines that do not contain that string will be added to file 2.
So, here is where I'm stuck. Everything works fine except the part where I want to delete file 1 and rename file 2 by file 1 (i.e item.txt). Can someone please help me with any correction? I am still a beginner in Java, so my code might not be the best looking code as one might expect but this is what I tried so far. Thanks
The problem is when i compile the code the updated data is written to file2 and file1 which was supposed to get deleted doesn't delete. So, what could be the problem?
package project4;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Scanner;
public class kitkat {
PrintWriter out,in;
Scanner in;
Scanner temp;
File file1 = new File("item.txt");
File file2 = new File("temp.txt");
public void write() throws FileNotFoundException {
out = new PrintWriter(file1);
out.println("User1"+ "\t"+"639755"+"\t"+"400");
out.println("User2"+ "\t"+"639725"+"\t"+"800");
out.close();
}
public void nfile() throws IOException {
n = new PrintWriter(new FileWriter(file2,true));
}
Scanner input = new Scanner(System.in);
String replacement = "User3";
String search;
String total;
public void search() {
System.out.println("Enter your search name");
search = input.nextLine();
total = search;
}
public void lolipop() throws IOException {
in = new Scanner(file1);
search();
while(in.hasNext()) {
String a,b,c;
a = in.next();
b = in.next();
c = in.next();
if(a.contains(search)) {
System.out.println("Your match is found"+search);
a = replacement;
System.out.println(a+b+c);
n.file();
n.println(a+"\t"+b+"\t"+c);
n.close();
}
}
}
public void jellybeans() throws IOException {
temp = new Scanner(file1);
while(temp.hasNext()) {
String p,q,r;
p = temp.next();
q = temp.next();
r = temp.next();
if(!(p.contains(total))) {
System.out.println(p+q+r);
n.file();
n.println(p+"\t"+q+"\t"+r);
n.close();
renamefile();
}
}
}
public void renamefile() {
file1.delete();
file2.renameTo(file1);
}
}
package project4;
import java.io.FileNotFoundException;
import java.io.IOException;
public class tuna {
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
kitkat kt = new kitkat();
kt.lolipop();
kt.jellybeans();
}
}
Change this:
public void renamefile() {
String file1Path = file1.getAbsolutePath();
file1.delete();
file2.renameTo(new File(file1Path));
}
According to the Javadoc of File.renameTo(…) the behavior of this method is platform dependent. If the rename does not succeed it simply returns false without throwing an exception. So I guess this would be the case here.
You can try the newer (since Java 7) Files.move(…). This method is platform independent and has propper error handling, throwing exceptions with a problem description.

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();
}
}
}

Cannot return result from System.in InputStreamReader

I'm having trouble just return the string of the color. For some reason it will not return the num. Not sure if I need to insert the end of the if statement with an else but I feel like that what the catch statement if for.
Main Class
package edu.computer.test;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Computer {
public Computer() {
}
public String getProcessor() {
InputStreamReader in = new InputStreamReader(System.in);
BufferedReader keyboard = new BufferedReader(in);
String num = null;
System.out.println("Type red to print red or blue to print blue");
try {
num = keyboard.readLine();
if (num.equals("red"))
num = "red";
if (num.equals("blue"))
num = "blue";
} catch (IOException e) {
System.out.println("Exception occured!");
}
return num;
}
}
Test Class
package edu.computer.test;
public class ComputerTester {
public static void main(String[] args) {
Computer a = new Computer();
a.getProcessor();
}
}
Your code example works just fine. I added the following line to your test and it printed the colour as expected:
public static void main(String[] args) {
Computer a = new Computer();
System.out.println(a.getProcessor());
}
Prints blue or red as appropriate.

Is there a way to make this Java program more interactive?

I have written the following very simple Java program to ask user enter a file name, then it will report the number of lines of this file to the standard output:
import java.io.*;
import java.util.*;
public class CountLine {
public static void main(String[] args)
{
// prompt the user to enter their file name
System.out.print("Please enter your file name: ");
// open up standard input
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String fileName = null;
// read the username from the command-line; need to use try/catch with the
// readLine() method
try {
fileName = br.readLine();
} catch (IOException ioe) {
System.out.println("IO error trying to read your name!");
System.exit(1);
}
System.out.println("Thanks for the file name, " + fileName);
File file = new File("C:/Users/Will/Desktop/"+fileName);
Scanner scanner;
try {
scanner = new Scanner(file);
int count =0;
String currentLine;
while(scanner.hasNextLine())
{
currentLine=scanner.nextLine();
count++;
}
System.out.println("The number of lines in this file is "+count);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
System.out.println("There is no such file");
e.printStackTrace();
}
}
}
It is working.I would be really thankful if experts could help me
see if there is anything that can be improved in this code fragment,
If the file is not found, the exception is caught in the outermost catch statement and print out the stack trace. However, I think it is not very user-friendly, is there a way if the file does not exist, then the whole process restarts from beginning?
Thanks in advance.
Get some Structure in your code:
public static void main(String[] args)
{
string output;
string fname = readFileName();
if (fileValid(fname)) //Ensure FileExists
{
int lineCount = scaneFile(fname);
output = "some output text including line numbers"
}
else
{
output = "File Not Valid..."
}
//showOutput...
}
Obvious change is to make a method countLines(String filename) that contains most of the code currently in main(). Obviously main() will call countLines().
Prompting for a file could live in main() or another method.
To restart on error you need a loop like:
filename = // read filename from stdin;
while(keepGoing(filename)) { // null check or whatever to let you out of the loop
try {
int numLines = countLines(filename);
println("num lines in " + filename + "=" +numLines);
}
catch(Exception ex) { // or just specific excpetions
ex.printStackTrace();
}
}
Unless you want to make a GUI. I suggest you receive the path to the file as a command line parameter.
If file doesn't exist print a message and exit. That's all.
The command line will give the user the option to move up with the up-key, edit the name and run again.
This class is named LineCounter and is the "business logic"
package countlines;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
public class LineCounter {
private int lineCount = 0;
public LineCounter(File file) throws IOException{
BufferedReader inFile = new BufferedReader(new FileReader(file));
while(inFile.readLine() != null) {
lineCount++;
}
inFile.close();
}
public int getLineCount() {
return lineCount;
}
}
This class is the "presentation logic"
package countlines;
import java.io.File;
import java.io.IOException;
public class Main {
public static void main (String[] args){
if (args.length != 1){
System.out.println("Usage: java countlines/Main filePath");
System.exit(1);
}
File f = new File(args[0]);
if (!f.exists()){
System.out.println("File "+f.getAbsolutePath()+" doesn't exist");
System.exit(2);
}
if (f.isDirectory()){
System.out.println(f.getAbsolutePath()+" is a directory");
System.exit(2);
}
LineCounter c;
try {
c = new LineCounter(f);
System.out.println(c.getLineCount());
} catch (IOException e) {
System.out.println("Error reading file " + f.getAbsolutePath());
}
}
}

Categories

Resources