I was wondering if anyone could help solve this NoSuchElements exception in my program which scans a text very large text and then is added to the ArrayList.
I have tried re-arranging the order of the code to see if that would fix it but now I don't know how to fix it.
Exception itself:
Exception in thread "main" java.util.NoSuchElementException
at java.base/java.util.Scanner.throwFor(Scanner.java:937)
at java.base/java.util.Scanner.next(Scanner.java:1478)
at mainTest.main(mainTest.java:11)
mainTest class:
import java.io.*;
import java.util.*;
public class mainTest {
public static void main(String args[]) throws FileNotFoundException {
ArrayList<String> bigBoi = new ArrayList<>(500000);
Scanner scan1 = new Scanner(new File("LargeDataSet.txt"));
while (scan1.hasNextLine()) {
scan1.next();
String data = scan1.next() + " " + scan1.next();
bigBoi.add(data);
}
ArrayList<String> successful = new ArrayList<>(500000);
}
}
The unit of a .txt file :
https://drive.google.com/file/d/1MWfMKMhSvuopOt9WwquABgYBTt0M4eLA/view?usp=sharing
(sorry for needing you to download it from a google drive, the file is so long I probably would've been reported or something if I had pasted 500,000 lines)
Please check with scan1.hasNext() instead of scan1.hasNextLine():
while (scan1.hasNext()) {
scan1.next();
String data = scan1.next() + " " + scan1.next();
bigBoi.add(data);
}
There is an empty line at the end of LargeDataSet.txt which is valid for scan1.hasNextLine() check, but the scan1.next() throws NoSuchElementException as there's nothing to read.
Changing validation to scan1.hasNext() as suggested in the accepted answer, solves that problem, but the program could still crash if there are less than 3 entries on any line and accepts lines with more than 3 entries.
A better practice is to validate all externally supplied data:
while (scan1.hasNextLine()) {
String line = scan1.nextLine();
String[] tokens = line.split("\\s+"); //split by space(s)
if(tokens.length != 3) { //expect exactly 3 elements on each line
throw new IllegalArgumentException("Invalid line: " + line);
}
bigBoi.add(tokens[1] + " " + tokens[2]);
}
Related
I cannot explain my problem very well, this is the prompt.
I believe I am going in the right direction, my professor really went through this fast. Even though I am using the book and asking for help, it is to no avail.
'**Ask the user to enter a filename on the keyboard, including “.txt.” Read five integers from that file (all on the same line, separated by spaces) and tell the user their sum by printing it to the screen (console).**'
It compiles and runs, but when entering the filename(io.txt) I get an Exception in thread "main" java.util.NoSuchElementException: No line found
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
String myString = " ";
Scanner inputStream = null;
System.out.println("Please enter a Filename, including '.txt' at the end: ");
myString = in.next();
try
{
inputStream = new Scanner(new FileInputStream(myString));
}
catch(FileNotFoundException e) //Giving the file not found a name,
{
System.out.println("Invalid File or filename");
System.out.println("Or could not be found,try again");
System.exit(0);
}
//True will always add on, not overwrite
int n1 = inputStream.nextInt();
int n2 = inputStream.nextInt();
int n3 = inputStream.nextInt();
int n4 = inputStream.nextInt();
int n5 = inputStream.nextInt();
String line = inputStream.nextLine(); //wait for new line, get the next line
inputStream.close( );
System.out.println("The five numbers read from the file are: ");
System.out.println(n1+" , "+ n2 + ", "+ n3 + ", "+ n4 +", "+ n5);
System.out.println("Which adds together to eqaul: " + (n1+n2+n3+n4+n5));
}
I want direction, not for someone to solve it for me.
After testing the code you gave it returns with
Exception in thread "main" java.util.NoSuchElementException: No line found
at java.util.Scanner.nextLine(Scanner.java:1540)
at com.example.Test.main(Test.java:37)
which is the following line in your code
String line = inputStream.nextLine(); //wait for new line, get the next line
So your code tries to read another line from the file, but it can't find one. In reality what this means is your code is expecting to read
"1 2 3 4 5\n" from a file io.txt whereas the file actually contains "1 2 3 4 5" (no newline at the end of the file).
However since you've already read all the integers you needed you can simply stop there.
Also make sure to close your file stream.
Use in. nextLine() in place of in. next().
I need to make a program where a user can input a name, and the program will search through the file line by line until it has a match, then return all the match. So this is what i Have, I got the file into the program, but cant seem to code the program to search the file for the user input. Any help?
Assignment: this what the code has to be able to do.
read in each row, parse out the name part, perform a match on names, if match return full name, else move to next row. Have message if you reach the end without a match.
import java.util.Scanner;
import java.io.*;
public class USpres {
public static void main(String[] args) throws FileNotFoundException {
File file = new File ("USPres.txt");
Scanner kb = new Scanner(System.in);
Scanner scanner = new Scanner(file);
System.out.println("Please enter the name you would like to search for: ");
String name = kb.nextLine();
while (scanner.hasNextLine())
{
if(scanner.nextLine() == kb)
{
System.out.println("I found " +name+ " in file " +file.getName());
}
break;
if(scanner.nextLine() == kb)
{
System.out.println("I found " +name+ " in file " +file.getName());
}
should become
if(scanner.nextLine().equalsIgnoreCase(name))
{
System.out.println("I found " +name+ " in file " +file.getName());
}
just like they said above in the comments. Also, .equals() is meant to compare two Objects, not two strings. Since they are both strings, you may have success with this method, but I would suggest always using .equalsIgnoreCase() when comparing Strings.
I am trying to read information from a file to interpret it. I want to read every line input. I just recently learned about bufferedreader. However, the problem with my code is that it skips every other line.
For example, when I put in 8 lines of data, it only prints 4 of them. The even ones.
Here is the code:
import java.io.*;
import java.util.Scanner;
public class ExamAnalysis
{
public static void main(String[] args) throws FileNotFoundException, IOException
{
int numOfQ = 10;
System.out.println();
System.out.println("Welcome to Exam Analysis. Let’s begin ...");
System.out.println();
System.out.println();
System.out.println("Please type the correct answers to the exam questions,");
System.out.print("one right after the other: ");
Scanner scan = new Scanner(System.in);
String answers = scan.nextLine();
System.out.println("What is the name of the file containing each student's");
System.out.print("responses to the " + numOfQ + " questions? ");
String f = scan.nextLine();
System.out.println();
BufferedReader in = new BufferedReader(new FileReader(new File(f)));
int numOfStudent= 0;
while ( in.readLine() != null )
{
numOfStudent++;
System.out.println("Student #" + numOfStudent+ "\'s responses: " + in.readLine());
}
System.out.println("We have reached “end of file!”");
System.out.println();
System.out.println("Thank you for the data on " + numOfStudent+ " students. Here is the analysis:");
}
}
}
I know this may be a bit of a bad writing style. I am just really new to coding. So if there is any way you can help me fix the style of the code and methods, I would be really thrilled.
The point of the program is to compare answers with the correct answer.
Thus I also have another question:
How can I compare strings with the Buffered Reader?
Like how can I compare ABCCED with ABBBDE to see that the first two match but the rest don't.
Thank you
the problem with my code is that it skips every other line
Your EOF check thows a line away on each iteration
while ( in.readLine() != null ) // read (first) line and ignore it
{
numOfStudent++;
System.out.println("Student #" + numOfStudent+ "\'s responses: " +
in.readLine()); // read (second) next line and print it
}
to read all line do the following:
String line = null;
while ( null != (line = in.readLine())) // read line and save it, also check for EOF
{
numOfStudent++;
System.out.println("Student #" + numOfStudent+ "\'s responses: " +
line); // print it
}
To compare Strings you need to use the String#compareTo(String other) method. Two Strings are equal if the return value is 0.
You don't compare Strings with readLine(). You compare them with String.equals().
Your reading code skips every odd line for the reason mentioned in the duplicate.
I am doing a tutorial on java and the video I am at now deals with FileReading, but it is for windows and I am on a mac. Please help
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class App {
public static void main(String[] args) throws FileNotFoundException {
String fileName = "/Users/--MyUsername--/Desktop/test.rtf";
File textFile = new File(fileName);
Scanner in = new Scanner(textFile);
int value = in.nextInt();
System.out.println("Read value: " + value);
in.nextLine();
int count = 2;
while(in.hasNextLine()){
String line = in.nextLine();
System.out.println(count + ": " + line);
count++;
}
in.close();
}
}
and this is the error that I am getting
Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Scanner.java:840)
at java.util.Scanner.next(Scanner.java:1461)
at java.util.Scanner.nextInt(Scanner.java:2091)
at java.util.Scanner.nextInt(Scanner.java:2050)
at L37ReadingTextFiles.App.main(App.java:17)
Please help
You are trying to read integers from the file, but the content is not integer, please use String value = in.next(); instead of int value = in.nextInt();
The problem is probably with the .rtf file. There might be a way to get that type of file to work as expected in java, but for a beginner, I would recommend making it a .txt file.
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 8 years ago.
So I'm trying to take a series of "scores" from a text file to put into an array and then sort in order, rows of four, and write other methods to get the highest, lowest, average, etc. The println commands are in there but I haven't written the methods yet. I've been working all day and I'm starting to confuse myself, and now I'm getting a NullPointerException error in the main method. Any help?
package arrayops1d;
import java.io.*;
import java.util.*;
public class ArrayOps1D {
static int scores[];
public static void main(String[] args) throws Exception{
FileReader file = new FileReader("C:/Users/Steve/Documents/"
+ "NetBeansProjects/ArrayOps1D/Scores.txt");
BufferedReader reader = new BufferedReader(file);
String scores = "";
String line = reader.readLine();
while (line != null){
scores += line;
line = reader.readLine();
}
System.out.println(scores);
System.out.println(getTotal());
System.out.println(getAverage());
System.out.println(getHighest());
System.out.println(getLowest());
System.out.println(getMedian());
System.out.println(getPosition());
System.out.println(getDeviations);
System.out.println(getStdDev);
}
Here is one way you can read the int values from a file into an array of Integer using a Scanner and a List -
Integer[] scores = null;
File file = new File("C:/Users/Steve/Documents/"
+ "NetBeansProjects/ArrayOps1D/Scores.txt");
if (file.exists() && file.canRead()) {
try {
List<Integer> al = new ArrayList<>();
Scanner scanner = new Scanner(file);
while (scanner.hasNext()) {
if (scanner.hasNextInt()) {
al.add(scanner.nextInt());
} else {
System.out.println("Not an int: " + scanner.next());
}
}
scores = al.toArray(new Integer[al.size()]);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
} else {
System.out.println("Can't find file: " + file.getPath());
}
if (scores != null) {
System.out.println("Scores Read: " + Arrays.toString(scores));
}
First Issue with your code:
In your file path, Instead using / , you must use \\ or better File.separator if your program wants to be ran in different platform.
If you do not , you will have java.io.FileNotFoundException
You are reading line by line, so you can use split Function and use Integer.paraseInt or Float.parseFloat to convert each splited elements and added to your array
How to use Split in Java
How to convert String to int