Java - Error: NoSuchElementException: No Line Found - java

I need to read strings from a file and store them in an array. However, my professor isn't allowing the class to use ArrayList. So I decided to run through the file once using hasNextLine() and counting how many lines there are then creating an array and making it equal to the amount of lines.
Then I made a while loop that is checking whether i is <= to the array, and giving the array[i] a value of fileInput.nextLine();. However, I seem to constantly get the error NoSuchElementException: No line found.
Here is my code:
public static void main(String[] args) throws FileNotFoundException {
int count = 0;
int i = 1;
//Read strings from a file and store in array
Scanner fileInput = new Scanner(new File("file.dat"));
while(fileInput.hasNextLine()) {
fileInput.nextLine();
count++;
}
String [] strArray = new String [count];
while (i <= strArray.length) {
/*Error Here*/ strArray[i] = fileInput.nextLine();
System.out.println(strArray[i]);
i++;
}
}
}
Would anyone know of a solution to my error?
P.S file.dat looks like this:
FRESH
MEAT
EVERY
SATURDAY
AT
TWELVE

Found the error. The problem ended up being that I need to create a new scanner class.

The Condition is wrong Here
while (i <= strArray.length)
You can write
while (i < strArray.length)

As you pointed out, the scanner cannot be reused. Since it reached the end of the file already.
Here is an alternative solution using standard Java 7 NIO:
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.*;
import java.util.Arrays;
public
class Reader
{
public static void main(String[] args) throws IOException
{
Path path = FileSystems.getDefault().getPath("file.dat");
Object[] myLines = Files.readAllLines(path, StandardCharsets.US_ASCII).toArray();
System.out.println(Arrays.toString(myLines));
}
}

As you know the index of an array in java starts with zero so the last elements index will always be lengthOfArray - 1
When you do this
while (i <= strArray.length)
Suppose your array contains 7 elements so the first element will be at zero index and it keep on adding the elements. Then a condition comes when i becomes 7 but still your while loop allows it because you have specified i <= strArray.length so it tries to add an element at seventh index but the last index of an array will always be lengthOfArray - 1 in this example it will be 6 so it cannot find the seventh index and will throw an exception.
To solve this just remove the equal sign
Scanner scannerForReading = new Scanner(new File("file.dat"));
while (i < strArray.length && scannerForReading.hasNextLine()) {
strArray[i] = scannerForReading.nextLine();
System.out.println(strArray[i]);
i++;
}

Related

How to sum up all ints in a text file?

I need to pull integers from a text file and sum them up. I came up with this but I keep getting an error. What am I missing? I need to use a scanner class.
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class txtClass {
public static void main(String[] args) throws FileNotFoundException {
File txtFile = new File(//text file path//);
Scanner scan = new Scanner(txtFile);
int length = 0;
while(scan.hasNextLine()) {
scan.nextLine();
length++;
}
int array[] = new int [length];
array[length++] = scan.nextInt();
System.out.println(array.toString());
int h = 0;
for (int i = 0; i<array.length; i++)
{
h +=array[i];
}
scan.close();
System.out.print(h);
}
}
As suggested, a lot of the code is not really needed. But presumably the 'error' you get is array index out of bounds. Here:
int array[] = new int [length];
array[length++] = scan.nextInt();
So you allocate an array and immediately access off the end of the array. Let's assume length is 42. Therefore, the allocated array elements have indexes 0 to 41. You try and assign something to array[42]. I'm not sure what you're trying to do with that line.
The alternative guess (which we would not need to guess had you mentioned the actual error message) is that your counting lines leaves the scanner positioned at end of file. so the scan.nextInt() call in the assignment gets you an I/O error.
In any case, the core of the solution is something like
int sum = 0;
while (scan.hasNextInt())
sum += scan.nextInt();
No array is needed.
You wrote in your question
I keep getting an error
That would be NoSuchElementException which is thrown by this line of your code:
array[length++] = scan.nextInt();
This is because you have already scanned the entire file and therefore there is no next int.
Remember that in order for people to help you with errors thrown by your code, you need to post the actual exception and the stack trace as well as your code.
You don't need to save all the numbers in the file in an array in order to get the sum of all the numbers. However if you also want to save all the numbers but you don't know in advance how many there are, you can use a List.
Here is a minimal example of how to read the file – which I assume contains only numbers separated by whitespace – and calculate the total. Of-course you need to replace text file path with the actual path to the text file.
File txtFile = new File("text file path");
try (Scanner scan = new Scanner(txtFile)) {
int total = 0;
while (scan.hasNextInt()) {
total += scan.nextInt();
}
System.out.println("Total: " + total);
}
catch (FileNotFoundException xFileNotFound) {
xFileNotFound.printStackTrace();
}
Note that the above code uses try-with-resources.

Java issues with Scanner and hasNextLine() while reading a file

I am having an issue with this unfinished program. I do not understand why this returns a "no Line found exception" when I run it. I have a while loop set up whose purpose is checking for this but I have done something wrong. I am trying to store information from a file into a 2d array for class.
import java.util.Scanner;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.File;
import java.util.Arrays;
public class LabProgram {
public static void main(String[] args) throws IOException {
Scanner scnr = new Scanner(System.in);
int NUM_CHARACTERS = 26; // Maximum number of letters
int MAX_WORDS = 10; // Maximum number of synonyms per starting letter
String userWord = (scnr.next()) + ".txt"; //Get word user wants to search
char userChar = scnr.next().charAt(0); //Get char user wants to search
String[][] synonyms = new String[NUM_CHARACTERS][MAX_WORDS]; // Declare 2D array for all synonyms
String[] words = new String[MAX_WORDS]; // The words of each input line
File aFile = new File(userWord);
Scanner inFile = new Scanner(aFile);
while(inFile.hasNextLine()) {
for(int i = 0; i < synonyms.length; i++) {
words = inFile.nextLine().trim().split(" ");
for(int wordCount = 0; wordCount < words.length; wordCount++) {
synonyms[i][wordCount] = words[wordCount];
}
}
}
}
}
The issue is with this for loop:
for (int i = 0; i < synonyms.length; i++) {
words = inFile.nextLine().trim().split(" ");
....
}
You're iterating from i=0 upto synonym.length-1 times, but that file does not have these much lines, so, as soon as your file is out of lines but the for loop has scope to iterate more, the inFile.nextLine() gets no line and thus throw the exception.
I don't know what you are exactly doing here or want to achieve through this code, but this is what causing you the trouble.
Hope that answers your query.
Basically your problem is that you're only checking hasNextLine() before the for loop starts, and you're actually getting the next line on every iteration of the loop. So if you run out of lines while in the middle of your for loop an exception is thrown.
I'm actually not quite sure what your code is supposed to do but at the very least you need to add a hasNextLine() check every time before you actually run nextLine() to avoid errors like this.

Item Counter program that will display the number of names that are stored on a file

Can someone help me with this java program that I've been puzzled on for a while. I'll post the question alone with the code but its a Files in java that I've recently started and I'm having trouble adding a loop counter variable to hold and display the number of names stored in the file.
For better understanding here the question I'm working on:
Assume that a file containing a series of names (as strings) is named names.dat and exists on the computers disk. Design a program that displays the number of names that are stored in the file. (Hint: Open the file and read every string stored in it. Each time you read a string, increment a counter variable. When you've read all the strings from the file, the counter variable will contain the number of names stored in the file.)
I don't know how much trouble it will be to aid assist being that this question is file related in java.
Here is my java code so far for better understanding:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class Item_Counter {
public static void main(String[] args) throws FileNotFoundException {
int numLines = 0;
int sum = 0;
File namesFile = new File("C:\\Users\\Tyrese\\JAVA 2\\Chapter 10\\names.dat");
Scanner bot = new Scanner(namesFile);
System.out.println(bot.nextLine());
while (bot.hasNext()) {
numLines = numLines + 1;
numLines = bot.nextInt();
}
System.out.println("The file has" + numLines);
}
}
Feel free to replace my file path and name that is a simple notepad document containing a few names, with your own if necessary.
You have some errors in your code, the way Scanner works for file reading is simple, you open the file the way you did like this : Scanner bot = new Scanner(namesFile); but in order to go to the next line you need to do bot.nextLine() so if you do it before you are in the while or do it twice it will go on 2 lines, so you just need to do like this :
public static void main(String[] args) throws FileNotFoundException {
int numLines = 0; // initialise variable
File namesFile = new File("C:\\Users\\Tyrese\\JAVA 2\\Chapter 10\\names.dat"); // fetch the file
Scanner bot = new Scanner(namesFile); // open the file
while (bot.hasNextLine()) { // while the file has a next line -> go on
numLines++; // add +1 to the variable numLines
numLines = bot.nextLine(); // go to the next line (if it has one)
}
System.out.println("The file has" + numLines); // print the result
}
You can ask me if you have any further questions
This is the problematic part of your code:
System.out.println(bot.nextLine());
while (bot.hasNext()) {
numLines = numLines + 1;
numLines = bot.nextInt();
}
Your println types a line being read and therefore that line will be ignored later. You need hasNextLine in the while loop and nextLine instead of nextInt.
Fix:
while (bot.hasNextLine()) {
numLines = numLines + 1;
bot.nextLine();
}
You can compute the sum of integers inside a file similarly. However, the actual solution depends on the structure of the file. If the file contains the integers as lines, without white characters beside the newline, such as
1
5
4
7
2
7
then the solution is:
int sum = 0;
while (bot.hasNextLine()) {
sum += 1;
bot.nextLine();
}
however, if the file is a list of numbers, separated by space, such as
3 7 8 2 8 3 6 9
then you read the content of the file via
String content = bot.nextLine();
String[] splited = str.split("\\s+");
int sum = 0;
for (int index = 0; index < splited.length; index++) {
sum += Integer.parseInt(splited[index])
}

Print Total Number of Different Words (case sensitive) from a file

**Edit after reviewing Tormod's answer and implementing his advice.
As the title states I'm attempting to print the total number of different words after receiving a file name from command line input. I receive the following message after attempting to compile the program:
Note: Project.java uses unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details.
Here is my code. Any help is greatly appreciated:
import java.lang.*;
import java.util.*;
import java.io.*;
public class Project {
public static void main(String[] args) throws IOException {
File file = new File(args[0]);
Scanner s = new Scanner(file);
HashSet lib = new HashSet<>();
try (Scanner sc = new Scanner(new FileInputStream(file))) {
int count = 0;
while(sc.hasNext()) {
sc.next();
count++;
}
System.out.println("The total number of word in the file is: " + count);
}
while (s.hasNext()) {
String data = s.nextLine();
String[] pieces = data.split("\\s+");
for (int count = 0; count < pieces.length; count++)
{
if(!lib.contains(pieces[count])) {
lib.add(pieces[count]);
}
}
}
System.out.print(lib.size());
}
}
I would implement it using a HashSet Add all the words, and read out the size. If you want to make it case insensitive just manipulate all the words to uppercase or something like that. this uses some memory but...
one problem you got with the algorithm is that you do only have one "words". it only holds the words at the same line. so you only count same words at the same line.
HashSet stores strings by their hash value, and thus stores one word only one time.
construction: HashSet lib = new HashSet<>();
inside the loop: if(!lib.contains(word)){lib.add(word);}
check the word count: lib.size()
for(String s : words) {
if(s.equals(word))
count++;
}
You are comparing the words to an empty String, since it's a word it's always gonna be false.
Like Tormod said, the best would be to store the words in a HashSet, as it won't keep duplicates. Then just read out its size.

Java: How come I can't output my sorted values from a csv file?

I have a program that reads from a csv file full of peoples last names, first names, and birth years, assigns them into a special class array, and then gets sorted according to their last name. I believe that my code is working, so all I have to do to verify this is output the list and see if indeed all of the people were sorted by their last name. However, I am having trouble finding the right syntax to do this.
Here is the code of my Main.java, where I think the issue must be.
package project_1_sorting;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Main
{
public static void main(String[] args) throws IOException {
// open file input stream
BufferedReader reader = new BufferedReader(new FileReader(
"C:\\Users\\Owner\\Desktop\\Data 18k.csv")); // double check where this is trying to read it from
// read file line by line
String line = null;
Scanner scanner = null;
int index = 0;
Human[] pplArray = new Human[18000];
int i = 0;
while ((line = reader.readLine()) != null) {
Human ppl = new Human();
scanner = new Scanner(line);
scanner.useDelimiter(",");
while (scanner.hasNext()) {
String data = scanner.next();
if (index == 0)
ppl.setLastName(data);
else if (index == 1)
ppl.setFirstName(data);
else if (index == 2)
ppl.setBirthYear(data);
else
System.out.println("invalid data::" + data);
index++;
}
ppl.setKey(0); //change this for later things, you can use loop
ppl.setOrder(0); //change this to 1 if you want to invert the list of people
index = 0;
pplArray[i] = ppl;
i++;
System.out.println(pplArray);
}
//close reader
reader.close();
System.out.println(pplArray); // create
Selection_Sort selection = new Selection_Sort();
for (int j = 0; j < 18000; j++)
{
System.out.println(pplArray[j]);
}
}
}
So I was expecting this to output a giant list of all of my people from the csv file(ordered), with all of their info in the same format as they originally were, right. (one person per row, with 3 collumns for their 3 strings). However this is what I got instead:
run:
Test
17
true
0.142857
BUILD SUCCESSFUL (total time: 0 seconds)
I am not sure what the meaning of this is. It would seem that its doing something completely unrelated to what I am trying to do. This is the only project that I have open in NetBeans, so it must be generated from my functions, right? If anyone knows what this is all about, please let me know. If there is nothing else wrong with this Main.java, I can post my other .java files.
One thing I did notice was that, even when I commented out my selection sort function call, and all of the printline commands in this .java file, the same output was displayed on my screen.
Please let me know what you think.
You have a few issues
The statements
Selection_Sort selection = new Selection_Sort();
for (int i = 0; i < 18000; i++)
{
System.out.println(pplArray[i]);
}
should be in the main18k method rather than the class block
Then the variable i has already been used so you need to use a different variable name either of those places where its used
for (int j = 0; j < 18000; j++)
Lastly use main instead of main18k so the application has a valid entry point
You have not close the bracket properly.Also variable i is used twice in the main method.So change the variable name.
Remove bracket before line Selection_Sort selection = new Selection_Sort();
Change the variable i to j and code is as below :
for (int j = 0; j < 18000; j++)
{
System.out.println(pplArray[j]);
}

Categories

Resources