'java.util.NoSuchElementException: No line found' using scanner class - java

I am getting this error when I try to run my program
Exception in thread "main" java.util.NoSuchElementException: No line found
at java.util.Scanner.nextLine(Scanner.java:1516)
at studenttextwrite.StudentDAO.open(StudentDAO.java:37)
at studenttextwrite.StudentTextWrite.main(StudentTextWrite.java:33)
Java Result: 1
I am trying to write an object to a txt file 'student.txt'. I have checked that the text file is in the correct folder, and that I have lines to be read. The program is supposed to read line by line and then create an object from those lines.
here is what the code looks like, any help would be greatly appreciated thanks.
public class StudentDAO implements DAO {
ArrayList<Student> studentList = new ArrayList();
String outputFileName = "student.txt";
File outputFile = new File(outputFileName);
Scanner in;
public StudentDAO() throws DAOException {
try {
in = new Scanner(new BufferedReader(new FileReader(outputFile)));
} catch (FileNotFoundException ex) {
throw new DAOException(ex.getMessage());
}
}
#Override
public void open() {
while (in.hasNextLine()) {
String studentName = in.nextLine();
String studentClass = in.nextLine();
String teacher = in.nextLine();
String studentAge = in.nextLine();
int studentAgeInt = Integer.parseInt(studentAge);
studentList.add(new Student(studentName, studentClass, teacher,
studentAgeInt));
}
}

while (in.hasNextLine()) {
String studentName = in.nextLine();
String studentClass = in.nextLine();
String teacher = in.nextLine();
String studentAge = in.nextLine();
}
You are doing hasNextLine() check only once. But you are reading 4 lines in.nextLine();.

The problem is your code assume that each student record consists of four lines, but you have less number of lines for a particular student. Consider a file that consist of following entries (left number is the line number):
a1
che
b1
21
a2
che
b2
22
a3
chem
b3
running the following code will create a similar error you have faced as there are only three lines for the third (a3) student. Check your input files.
while(in.hasNextLine()){
System.out.println(" "+in.nextLine());
System.out.println(" "+in.nextLine());
System.out.println(" "+in.nextLine());
System.out.println(" "+in.nextLine());
}

Related

How can I take a String with a name and two values and separate it into a String containing the name and 2 doubles containing the values?

I've written a class for a program designed to help manage a volleyball team's roster. The roster is contained in a .dat file and the players are written as follows:
Rachael Adams 3.36 1.93
My issue arises when I try to separate this string into the proper data types (the name being a string, then the first and second values being doubles for the stats).
public Roster(String filename) {
players = new ArrayList<Player>();
try {
FileReader fr = new FileReader(filename);
BufferedReader inFile = new BufferedReader (fr);
String line = inFile.readLine();
Scanner scan = new Scanner(line);
while(line != null) {
String firstName = scan.next();
String lastName = scan.next();
double attackStat = scan.nextDouble();
double blockStat = scan.nextDouble();
String name = firstName + " " + lastName;
Player newPlayer = new Player(name, attackStat, blockStat);
players.add(newPlayer);
line = inFile.readLine();
}
scan.close();
inFile.close();
} catch (IOException e) {
System.out.println(e);
}
}
The program throws this exception when a Roster object is created
Exception in thread "main" java.util.InputMismatchException
at java.base/java.util.Scanner.throwFor(Scanner.java:939)
at java.base/java.util.Scanner.next(Scanner.java:1594)
at java.base/java.util.Scanner.nextDouble(Scanner.java:2564)
at Roster.<init>(Roster.java:30)
at Assignment08.openRosterFile(Assignment08.java:59)
at Assignment08.main(Assignment08.java:18)
I am newer to Java and still facing a learning curve, so if there is more information needed then please let me know.
If at all possible, I would greatly appreciate an explanation as to what I did wrong rather than just a solution. Thank you very much.
I always find it easier to split the line:
String[] columns = line.split(" (?=\\d)";
String name = columns[0];
double attackStat = Double.parseDouble(columns[1]);
double blockStat = Double.parseDouble(columns[2]);
This works by splitting on a space, but only when the next char is a digit via the look ahead (?=\d).
This automatically caters for any number of words in the name.

Reading Text File into Array using Java generates Exception

Even though the file Movie_db.txt isn't empty, I get the following exception:
the text file consists of this:
hank horror 20.0 18 1
public void syncDB(List<Movie> movieList) throws IOException {
Scanner scanner = new Scanner("Movie_db.txt");
BufferedReader reader = null;
try {
String line = null;
String title;
String genre;
double movieDuration;
int ageRestriction;
int id;
while (scanner.hasNext()) {
title = scanner.next();
genre = scanner.next();
movieDuration = scanner.nextDouble();
ageRestriction = scanner.nextInt();
id = scanner.nextInt();
movieList.add(new Movie(title, genre, movieDuration, ageRestriction, id));
}
} catch (Exception e) {
System.out.println("List is empty");
}
}
Considering your path is correct, there is a problem in your code. I'd change this line
Scanner scan = new Scanner("Movie_db.txt");
with this one
Scanner scan = new Scanner(Paths.get("Movie_db.txt"));
The reason is that in your snippet the Scanner only reads the string "Movie_db.txt" and in the second snippet it recognizes as the path to file.
Read Scanner documentation for more info
genre = scan.next(); line is throwing exception because nothing is left to read from file now, which causes catch block to execute.
You are providing a string to Scanner which is a valid input for scanner. Hence, it never reads the file.
Scanner scan = new Scanner(new File("full_path_to_container_dir/Movie_db.txt"));
Please have a look at this blog on how to read from a file using scanner - https://www.java67.com/2012/11/how-to-read-file-in-java-using-scanner-example.html.

Creating a new array object is causing several errors to come up

Sorry if this is an easy fix, but I'm new to Java and I'm stumped.
As the title says, when I'm trying to create a new array on line 41 I get the following error:
Syntax error on token ";", { expected after this token
If I delete the semi-colon, I get three additional errors on lines 44, 48 and 51 which is in the try-catch block.
If I delete the entire line:
Reservation reservation[] = new Reservation[MAX_ARRAY_SIZE];
I get the same error message for the scanner object that is above the array on line 38.
Also, the final curly brace that is at the bottom of the class is also generating an error message saying that I need to add a curly brace, but that seems to be just an extra brace with no partner and does not remove any of the above errors.
I've attached all of my code for this class and can attach the reservation class upon request. Thanks in advance for any assistance.
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class AirlineInput
{
final int MAX_ARRAY_SIZE = 20;
final String DATA_FILE = "AirlineData.txt";
final String TRANSACTION_FILE = "Transactions.txt";
int count; //counter for array
File file = new File(DATA_FILE);
Scanner input = null;
//creating an array to store data from file
Reservation reservation[] = new Reservation[MAX_ARRAY_SIZE];
//opening file
try
{
input = new Scanner(file);
}
catch(FileNotFoundException e)
{
System.out.println(e.getMessage());
}
//file data being placed in array
while(input.hasNext())
{
String passengerName = input.nextLine();
String reservationNumber = input.nextLine();
String depatureFlight = input.nextLine();
String departureFlightDate = input.nextLine();
String departureAirport = input.nextLine();
String arrivalAirport = input.nextLine();
String departureTime = input.nextLine();
String arrivaltime = input.nextLine();
String seat = input.nextLine();
String returnFlight = input.nextLine();
String returnFlightdate = input.nextLine();
String returnDepartureAirport = input.nextLine();
String returnArrivalAirport = input.nextLine();
String returnDepartureTime = input.nextLine();
String returnArrivalTime = input.nextLine();
String returnSeat = input.nextLine();
}
}
Your code needs to be in a method inside of the AirlineInput class.
Usually, a class has a main method, which in your case would look like this:
public class AirlineInput {
public static void main(String[] args) {
// Code here
}
}

Scanner issue! Code is skipping the first user input and printing twice instead of once ONLY on the first iteration

https://courses.cs.washington.edu/courses/cse142/15sp/homework/6/spec.pdf
EDIT* Input Files are here:(sorry i'm new to stack overflow, hopefully this works)
I've also tried console.next() but it gives different errors than console.nextLine() in the rePlaceholder method. **
tarzan.txt - https://pastebin.com/XDxnXYsM
output for tarzan should look like this: https://courses.cs.washington.edu/courses/cse142/17au/homework/madlibs/expected_output_1.txt
simple.txt https://pastebin.com/Djc2R0Vz
clothes.txt https://pastebin.com/SQB8Q7Y8
this code should print to an output file you name.
Hello, I have a question about scanners because I don't understand why the code
is skipping the user input on the first iteration but works fine on the rest.
I'm writing a code to create a madlib program and the link will provide the explanation to the program but pretty much you have these placeholders in a text file and when you see one, you prompt for user input to replace it with your own words. However, my program always go through TWO placeholders first and only ask the user input for one, completely skipping the first placeholder. What is wrong with my code??? Also, how do you fix this? Everything else is running perfectly fine, only that the first line is consuming two placeholders so I'm always off by one.
Welcome to the game of Mad Libs.
I will ask you to provide various words
and phrases to fill in a story.
The result will be written to an output file.
(C)reate mad-lib, (V)iew mad-lib, (Q)uit? c
Input file name: tarzan.txt
Output file name: test.txt
Please type an adjective: Please type a plural noun: DD DDDD <--- why is it like this
Please type a noun: DDDD
Please type an adjective: DD
Please type a place:
========================================================================
package MadLibs;
import java.util.*;
import java.io.*;
public class MadLibs2 {
public static void main(String[] args) throws FileNotFoundException {
Scanner console = new Scanner(System.in);
intro();
boolean isTrue = true;
while(isTrue) {
System.out.print("(C)reate mad-lib, (V)iew mad-lib, (Q)uit? ");
String choice = console.next();
if (choice.equalsIgnoreCase("c")) {
create(console);
}
else if (choice.equalsIgnoreCase("v")) {
view(console);
}
else if (choice.equalsIgnoreCase("q")) {
System.exit(0);
}
}
}
public static void view(Scanner console) throws FileNotFoundException {
System.out.print("Input file name: ");
String viewFile = console.next();
File existingMadLib = new File(viewFile);
Scanner printText = new Scanner(existingMadLib);
while(printText.hasNextLine()) {
System.out.println(printText.nextLine());
}
}
public static void create(Scanner console) throws FileNotFoundException {
System.out.print("Input file name: ");
String inputFile = console.next();
File newMadLib = new File(inputFile);
while(!newMadLib.exists()) {
System.out.print("File not found. Try again: ");
inputFile = console.next();
newMadLib = new File(inputFile);
}
System.out.print("Output file name: ");
String outputFile = console.next();
System.out.println();
PrintStream output = new PrintStream(new File(outputFile));
Scanner input = new Scanner(newMadLib);
while(input.hasNextLine()) {
String line = input.nextLine();
outputLines(line, output, console);
}
}
public static void outputLines(String line, PrintStream output, Scanner console) throws FileNotFoundException{
String s = "";
Scanner lineScan = new Scanner(line);
while(lineScan.hasNext()){
s = lineScan.next();
if(s.startsWith("<") || s.endsWith(">")) {
s = rePlaceholder(console, lineScan, s);
}
output.print(s + " ");
}
output.println();
}
public static String rePlaceholder(Scanner console, Scanner input, String token) {
String placeholder = token;
placeholder = placeholder.replace("<", "").replace(">", "").replace("-", " ");
if (placeholder.startsWith("a") || placeholder.startsWith("e") || placeholder.startsWith("i")
|| placeholder.startsWith("o") || placeholder.startsWith("u")) {
System.out.print("Please type an " + placeholder + ": ");
} else {
System.out.print("Please type a " + placeholder + ": ");
}
String change = console.nextLine();
return change;
}
public static void intro() {
System.out.println("Welcome to the game of Mad Libs.");
System.out.println("I will ask you to provide various words");
System.out.println("and phrases to fill in a story.");
System.out.println("The result will be written to an output file.");
}
}
in your rePlaceholder, change this line:
String change = console.nextLine();
Into this
String change = console.next();
Your problem is that nextLine doesn't wait for your output, just reads what it has in the console, waiting for a new line.
This is from the documentation to be a bit more precise on the explanation:
Since this method continues to search through the input looking for a
line separator, it may buffer all of the input searching for the line
to skip if no line separators are present.
UPDATE
After reading the comment, the previous solution will not work for multiple words.
After reading the output file, you are using next().
You need to make another call to nextLine() to clean the buffer of any newlines.
System.out.print("Output file name: ");
String outputFile = console.next();
console.nextLine(); // dummy call
System.out.println();

Java - create an instance of file reader and output

I have a program which reads some data under a file reader and then creates an instance of another class which models the data. Anyway that class works (has been tested with some hard coded values) but I now want to output the data of the instance of a Patient being read under the file reader but seem unable to.
Could anyone tell me where i'm going wrong.
You are not adding Patient instances to newPatient collection, that's why it's empty and you are not getting anything printed out. Add elements to queue:
while(scan.hasNextLine()){
String firstname = scan.nextLine();
String surname = scan.nextLine();
String illness = scan.nextLine();
int illnessSeverity = scan.nextInt();
String newLine = scan.nextLine();
newPatient.add(new Patient(firstname,surname,illness,illnessSeverity));
for (Patient newPatientData : newPatient) {
System.out.println(newPatientData);
}
You need to add data first to the Priority Queue. I think you missed that .
PriorityQueue<Patient> newPatient = new PriorityQueue<>();
File fileName = new File("patients.txt");
Scanner scan = null;
try {
scan = new Scanner(fileName);
while(scan.hasNextLine()){
String firstname = scan.nextLine();
String surname = scan.nextLine();
String illness = scan.nextLine();
int illnessSeverity = scan.nextInt();
String newLine = scan.nextLine();
Patient newP = new Patient(firstname,surname,illness,illnessSeverity);
newPatient.add(newP);
}
for (Patient newPatientData : newPatient) {
System.out.println(newPatientData);
}
} catch(Exception e) {
System.out.println("ERROR - file not found");
}

Categories

Resources