Can someone please explain to me why I'm getting the catch error ?
I am trying to read values (numbers) from the file I passed in args.
And I do not quite understand where the problem comes from.
import java.util.Scanner;// Import the Scanner class to read text files
import java.io.File;// Import the File class
import java.io.FileNotFoundException;// Import this class to handle errors
import java.io.*;
public class main extends GeneralMethods {
public static void main(String[] args) {
if (args.length <= 1 || args.length > 2) {
println("Error, usage: software must get two input files");
System.exit(1);
}
String file_name1 = args[0]; // data to insert
String file_name2 = args[1]; // data to check
File data_to_insert = new File(file_name1);
File data_to_check = new File(file_name2);
Scanner input = new Scanner(System.in); // Create a Scanner object
println("Enter hashTable size");
int hashTable_size = input.nextInt(); // Read hashTable_size from user
println("Enter num of hashing function");
int num_of_has = input.nextInt(); // Read num of hashing from user
hashTable T = new hashTable(hashTable_size);
println("hashTable before insert values\n");
T.printHashTable();
input.close();
int i = 0;
try {
input = new Scanner(data_to_insert);
String data;
while ((data = input.next()) != null) {
T.set(i, Integer.parseInt(data));
i++;
}
input.close();
} catch (Exception e) {
System.out.println("\nError: Reading, An error occurred while reading input files. Check your input type");
e.printStackTrace();
}
T.printHashTable();
}
}
this is my output
Which prints the catch error
hashTable before insert values
[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]
Error: Reading, An error occurred while reading input files. Check your input type
java.util.NoSuchElementException
at java.base/java.util.Scanner.throwFor(Scanner.java:937)
at java.base/java.util.Scanner.next(Scanner.java:1478)
at main.main(main.java:36)
[1,2,3,4,5,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]
In this line,
while ((data = input.next()) != null)
The next() method of Scanner does not return null if it has no more data, instead it throws the NoSuchElementException you are getting.
Use this instead to check for more data:
while ((input.hasNext()) {
data = input.next();
//...
}
Method hasNext() returns true or false as you would expect.
Related
I am trying to write a program that inputs a text file through the command line and then prints out the number of words in the text file. I've spent around 5 hours on this already. I'm taking an intro class using java.
Here is my code:
import java.util.*;
import java.io.*;
import java.nio.*;
public class WordCounter
{
private static Scanner input;
public static void main(String[] args)
{
if (0 < args.length) {
String filename = args[0];
File file = new File(filename);
}
openFile();
readRecords();
closeFile();
}
public static void openFile()
{
try
{
input = new Scanner(new File(file));
}
catch (IOException ioException)
{
System.err.println("Cannot open file.");
System.exit(1);
}
}
public static void readRecords()
{
int total = 0;
while (input.hasNext()) // while there is more to read
{
total += 1;
}
System.out.printf("The total number of word without duplication is: %d", total);
}
public static void closeFile()
{
if (input != null)
input.close();
}
}
Each way I've tried I get a different error and the most consistent one is "cannot find symbol" for the file argument in
input = new Scanner(new File(file));
I'm also still not entirely sure what the difference between java.io and java.nio is so I have tried using objects from both. I'm sure this is an obvious problem I just can't see it. I've read a lot of similar posts on here and that is where some of my code is from.
I've gotten the program to compile before but then it freezes in command prompt.
java.nio is the New and improved version of java.io. You can use either for this task. I tested the following code in the command line and it seems to work fine. The "cannot find symbol" error message is resolved in the try block. I think you were confusing the compiler by instantiating a File object named file twice. As #dammina answered, you do need to add the input.next(); to the while loop for the Scanner to proceed to the next word.
import java.io.File;
import java.io.IOException;
import java.util.Scanner;
public class WordCounter {
private static Scanner input;
public static void main(String[] args) {
if(args.length == 0) {
System.out.println("File name not specified.");
System.exit(1);
}
try {
File file = new File(args[0]);
input = new Scanner(file);
} catch (IOException ioException) {
System.err.println("Cannot open file.");
System.exit(1);
}
int total = 0;
while (input.hasNext()) {
total += 1;
input.next();
}
System.out.printf("The total number of words without duplication is: %d", total);
input.close();
}
}
Your code is almost correct. Thing is in the while loop you have specified the terminating condition as follows,
while (input.hasNext()) // while there is more to read
However as you are just increment the count without moving to the next word the count just increases by always counting the first word. To make it work just add input.next() into the loop to move to next word in each iteration.
while (input.hasNext()) // while there is more to read
{
total += 1;
input.next();
}
help im stuck.. we are to make two programs the 1st one we ask the user to input how many employees, 1st name, lastname, id,..then store it into a file called names.db. ...i was able to get this done...im stuck on the 2nd program...which suppose to do this....retrieve the employee database by asking the user to input the employees 1st name and if the employee is found then print that info...if not then print not found.
import java.util.Scanner;
import java.io.*;
public class RetrieveInfo
{
public static void main(String[] args) throws IOException
{
//create scanner object for keyboard input
Scanner keyboard = new Scanner(System.in);
//open file
File file = new File("Employee.db");
Scanner inputFile = new Scanner(file);
//ask for employee name
System.out.print("enter the name of the employee. ");
String firstName =keyboard.nextLine();
//here is where im stuck...read the file and check of the empoyee is
here. We are learning about loops some im pretty sure its going to be a loop
}
}
You should probably get through your lines and if the data is in the current line then print it. After reading your file :
String expectedemployee = null
for(String line : Files.readAllLines(Paths.get("/path/to/file.txt")) {
if(line.contains(firstName) {
expectedemployee = line;
break;
}
}
if(expectedemployee != null) {
// print
} else {
// you don't have any employee corresponding
}
Or you can use BufferedReader.
try (BufferedReader br = new BufferedReader(new FileReader(file))) {
String line;
while ((line = br.readLine()) != null || expectedemployee != null) {
if(line.contains(firstName) {
expectedemployee = line;
break;
}
}
}
Using Database rather than file would be better for this type.if you want files then you should try with Object Input/Output Stream.
I need to write a program that reads a text file and calculates different things, however, if the file name is not found, it should print an error message with the following error message from a try and catch block:
java.io.FileNotFoundException: inputValues (The system cannot find the file specfied)
.......
However, I am instead receiving this error message:
Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Unknown Source)
at java.util.Scanner.next(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
at Project6.main(Project.java:50)
Here is part of my code:
Scanner console = new Scanner(System.in);
System.out.print("Please enter the name of the input file: "); // Prompts User to Enter Input File Name
String inputFileName = console.nextLine(); // Reads Input File Name
Scanner in=null; //
try
{
in = new Scanner(new File(inputFileName)); // Construct a Scanner Object
}
catch (IOException e) // Exception was Thrown
{
System.out.print("FileNotFound Exception was caught, the program will exit."); // Error Message Printed because of Exception
e.printStackTrace();
}
int n = in.nextInt(); // Reads Number of Line in Data Set from First Line of Text Document
double[] array = new double[n]; // Declares Array with n Rows
Line 50 is: int n = in.nextInt();
Other than printing the incorrect error message, my program runs perfectly fine.
Any/all help would be greatly appreciated!
Your exception thrown at the line in.nextInt() where you are trying to read an integer but the scanner found something else. If you need to take all of them as a single error you can put them in the same try catch block as follows.
Scanner in=null; //
try
{
in = new Scanner(new File(inputFileName));
// Construct a Scanner Object
int n = in.nextInt();
// Reads Number of Line in Data Set from First Line of Text Document
double[] array = new double[n];
} catch (IOException e)
// Exception was Thrown
{
System.out.print("FileNotFound Exception was caught, the program will exit.");
// Error Message Printed because of Exception
e.printStackTrace();
} catch (InputMismatchException e)
// Exception was Thrown
{
System.out.print("Integer not found at the beginning of the file, the program will exit.");
// Error Message Printed because of Exception
e.printStackTrace();
}
Ugly, badly formatted code is hard to read and understand. It's part of why you're having trouble.
This is simpler: start with this.
package cruft;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
/**
* MessyFileDemo
* #author Michael
* #link https://stackoverflow.com/questions/31106118/try-and-catch-error-in-java
* #since 6/28/2015 8:20 PM
*/
public class MessyFileDemo {
public static void main(String[] args) {
List<Double> values;
InputStream is = null;
try {
String inputFilePath = args[0];
is = new FileInputStream(inputFilePath);
values = readValues(is);
System.out.println(values);
} catch (IOException e) {
e.printStackTrace();
} finally {
close(is);
}
}
private static void close(InputStream is) {
try {
if (is != null) {
is.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
public static List<Double> readValues(InputStream is) throws IOException {
List<Double> values = new ArrayList<>();
if (is != null) {
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String line;
while ((line = br.readLine()) != null) {
String [] tokens = line.split(",");
for (String token : tokens) {
values.add(Double.parseDouble(token));
}
}
}
return values;
}
}
I am trying to add objects to a queue from a data file which is made up of text which is made up of a person's first name and their 6 quiz grades (ie: Jimmy,100,100,100,100,100,100). I am accessing the data file using the FileReader and using BufferReader to read each line of my data file and then tokenize each line using the "," deliminator to divide the names and quiz grades up. Based on what I think my professor is asking for is to create a queue object for each student. The assignment says,
Read the contents of the text file one line at a time using a loop. In this loop, invoke the processInputData method for each line read. This method returns the corresponding Student object. Add this student object to the studentQueue.
If someone could point me the right direction that would be great! Here is my code so far:
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.StringTokenizer;
public class Test {
public static void main(String[] args) {
// Create an empty queue of student objects
LinkedList<Student> studentQueue;
studentQueue = new LinkedList<Student>();
// Create an empty map of Student objects
HashMap<String, Student> studentMap = new HashMap<String, Student>();
System.out.printf("Initial size = %d\n", studentMap.size());
// Open and read text file
String inputFileName = "data.txt";
FileReader fileReader = null;
// Create the FileReader object
try {
fileReader = new FileReader(inputFileName);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
// BufferReader to read text file
BufferedReader reader = new BufferedReader(fileReader);
String input;
// Read one line at a time until end of file
try {
input = reader.readLine();
while (input != null) {
processInputData(input);
input = reader.readLine();
}
}
catch (IOException e) {
e.printStackTrace();
}
// Close the input
try {
fileReader.close();
}
catch (IOException e) {
e.printStackTrace();
}
}
// Tokenize the data using the "," as a delimiter
private static void processInputData(String data) {
StringTokenizer st = new StringTokenizer(data, ",");
String name = st.nextToken();
String homework1 = st.nextToken();
String homework2 = st.nextToken();
String homework3 = st.nextToken();
String homework4 = st.nextToken();
String homework5 = st.nextToken();
String homework6 = st.nextToken();
// Using the set methods to correspond to the Student object
Student currentStudent = new Student(name);
currentStudent.setHomework1(Integer.parseInt(homework1));
currentStudent.setHomework2(Integer.parseInt(homework2));
currentStudent.setHomework3(Integer.parseInt(homework3));
currentStudent.setHomework4(Integer.parseInt(homework4));
currentStudent.setHomework5(Integer.parseInt(homework5));
currentStudent.setHomework6(Integer.parseInt(homework6));
System.out.println("Input File Processing...");
System.out.println(currentStudent);
}
}
One possible solution to your problem is returning the student in processInputData(..)
private static Student processInputData(String data) {
// the same code
return currentStudent;
}
And in while loop
while (input != null) {
studentQueue.add(processInputData(input));
input = reader.readLine();
}
Also try to manage better your try-catch blocks, cause if your fileReader throws exception then the code will continue running and throw probably a nullPointerException that you don't handle.
try{
fileReader = new FileReader(inputFileName);
BufferedReader reader = new BufferedReader(fileReader);
}catch(IOException ex){
//handle exception;
}finally{
// close resources
}
Is there a way to use a try/catch statement to ask the user to enter a file, if the user enters the wrong filename, the program will ask two more times, and then exit with an exception? How could I loop? Because once the user enters the wrong filename the program throws the exception immediately.
import java.io.File;
import java.io.FileNotFoundException;
import java.util.*;
import java.util.logging.Level;
import java.util.logging.Logger;
public class Main {
static String[] words = new String[5];
public static void main(String[] args)
{
Scanner kb = new Scanner(System.in);
System.out.println("enter file name:");
String fileName = kb.next();
try {
File inFile = new File(fileName);
Scanner in = new Scanner(new File(fileName));
} catch (FileNotFoundException ex) {
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
}
}
So you don't want it to throw any kind of error when the user enters the wrong filename, right? If so, then I think this is what you want:
for(int i = 0; i < 3; i++){
try {
File inFile = new File(fileName);
Scanner in = new Scanner(new File(fileName));
break;
} catch (FileNotFoundException ex) {
if(i == 2){
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
System.exit(0);
}
else
continue;
}
}
if the user enters the correct file name, it will break out of the loop. If not, it checks to see if the loop is on it's third iteration. If it is, (that means the user has tried and failed twice), it prints the error and exits the program. If the loop isn't on it's third iteration, it continues with the loop and re-prompts the user.
I hope it's obvious that the FileNotFoundException is thrown by the Scanner constructor. So why use it until you're sure the file exists? You shouldn't create the Scanner object till you got the correct file!
To implement this idea use this in your try block:
//read file name from stdio
File inFile = new File(fileName);
int i = 0;
while(!inFile.exists() && i++ < 2 ){
//read file name from System.in;
inFile = new File(fileName);
}
Scanner in = new Scanner(new File(fileName));
assuming you create a boolean fileIsLoaded = false, and set that to true. You can create a loop
for(int i=0;i<2 && !fileIsLoaded; i++) {
//your try/catch goes here
}
Enclose all of the code within your current main within that loop (with the boolean created beforehand). Finally, you can check the boolean afterwards in case all tries failed.