Why won't my method read in every value from a file? - java

public static int getBoys(ArrayList<String> boysNames, Scanner s) throws IOException {
// Getting boys file location
System.out.println("Please enter the file name containing the the boys names.");
String boyFileLocation = s.nextLine();
// Opening the file containing the names of boys
File boyFile = new File(boyFileLocation);
Scanner BF = new Scanner(boyFile);
int initialBoyCount = 0;
int i = 0;
boysNames.add(BF.nextLine());
while (BF.hasNextLine()) {
if (BF.nextLine().equals(boysNames.get(i))) {
} else {
boysNames.add(BF.nextLine());
initialBoyCount++;
i++;
System.out.println(boysNames.get(i));
}
}
return (initialBoyCount);
}
I am trying to read in from a file a list of names and add them to an array list. However there are duplicates of certain names and i am only suppoused to keep the unique ones (If if already exists don't add it again). However, I figured out that it is only giving me every other name. Starting with 2, and giving me the following errors.
Exception in thread "main" java.util.NoSuchElementException: No line found
at java.util.Scanner.nextLine(Scanner.java:1540)
at namesList.namesList.getBoys(namesList.java:53)
at namesList.namesList.main(namesList.java:27)

The reason of the exception in this line
if (BF.nextLine().equals(boysNames.get(i)))
you read a line and if equation isn't true in else branch you call BF.nextLine() again. So sometimes you read line twice but you call hasNextLine() only once .
Solution: read line only one time before if statement.

Related

I have read contents of a file which I have done and then add up all the numbers in the file and find the average

public static double value;
public static void main(String[] args) throws FileNotFoundException {
System.out.println("Enter the name of the file :");
Scanner scan = new Scanner(System.in);
String filename = scan.next();
Scanner bru = new Scanner (new File(filename));
int num = bru.nextInt();
System.out.println("The file "+ filename +" has "+ num +" numbers in it");
System.out.println("Content of file is");
double total = 0.0;
while(bru.hasNextDouble())
System.out.println(bru.nextDouble());
value = bru.nextDouble();
System.out.println(bru.nextDouble());
}
}
When I run my code I get this error
"
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:1594)
at java.base/java.util.Scanner.nextDouble(Scanner.java:2564)
at Project4.main(Project4.java:26)
"
If I add brackets to the while loop I don't get the error instead I it reads one double then skips the next and so on.
I'd suggest using your variable to print from, rather than how you are doing it now. The "bru.nextDouble" is getting the next value every time you use it, which is why you are skipping values when you add the brackets. The value of "value" is what you want to print, not the "nextDouble" before it.
while(bru.hasNextDouble())
{
value = bru.nextDouble();
System.out.println(value);
}
Also, with using "bru.nextDouble" as many times as you do after checking "bru.hasNextDouble", you run the risk of trying to access data/values not in "bru" causing any number of exceptions. And the exception you are getting, NoSuchElementException, is likely the very exception that says you have already run out of data/values when you try to get the next one.
So, you also need to get rid of your last "System.out.println(bru.nextDouble());" and you should be able to run your current code, with the minor adjustment I suggest, without any exceptions due to running out of values.
There may be other issues and exceptions with your code, but I/we won't know that until you fix the problem you currently have.

I'm getting a No Line Found error code via reading a text file

Odd error i'm getting. "No Line found". I tried commenting out my sem variable thinking that was the issue, however no dice. I have tried commenting out my String elements to see if those were the issue. Any help would be appreciated.
The error: Exception in thread "main" java.util.NoSuchElementException: No line found
at java.base/java.util.Scanner.nextLine(Scanner.java:1651)
at Driver2.main(Driver2.java:27)
The Txt File:
Kimberly Signwell
Sophomore
EDUC
3
Don Boss
Freshman
CPSC
1
Mayble Lently
Junior
MATH
6
Each element has their own line. The error seems to say that I don't have a third line, however, the txt file has more than 3 lines.
**public class Driver2
{
private static Student [] students = new Student[100];
private static Scanner kbd = new Scanner(System.in);
#SuppressWarnings("resource")
public static void main(String[] args) throws FileNotFoundException
{
FileReader file = new FileReader("students.txt");
Scanner in = new Scanner(file);
int i = 0;
while (in.hasNextLine())
{
String l1 = in.nextLine();
String l2 = in.nextLine();
String l3 = in.nextLine();
int sem = in.nextInt();
in.nextLine();
students[i++] = new Student(l1, l2, l3, sem);
}
runMenu();
System.out.printf("Program Finished");
}**
It might be because the hasNextLine() condition is checking for a single next line, but in the body of the loop, you are checking for the next four lines, which might give an error because if the program has reached suppose the second last line of the text file, the loop will execute because you do have another line of data, but the body of the loop demands for multiple lines of data...
The nextLine() function moves the cursor to the next line every time it is called, and not just once. Try watching some tutorials or reading docs for more understanding nextLine()

how to properly get every line containing a specific word in java

I'm trying to write a program that reads a file and checks every line that contains a specific word then prints it.if there isn't one it should print "no match for your search".this is what I've got so far and and I'm having trouble putting it all together.after all my twinkering around and replacing thewhile with ifor putting the second if statement outside of the while, sometimes it doesn't matter what i enter it always says "no match for your search" and sometimes it says java.util.NoSuchElementException: No line found. and sometimes it freezes and i searched this up and it says its a bug in cmd or something.any help will be appreciated
and I'm new to java so please any thing you can advise me will be helpful and appreciated
System.out.println("search for book");
String search = scan.next();
scan.nextLine();
File file = new File("library.txt");
Scanner in = null;
in = new Scanner(file);
String line = in.nextLine();
while(in.hasNext()) {
if(line.contains(search)) {
System.out.println(line);
}
if(!line.contains(search)) {
System.out.println("no match for your search");
System.exit(0);
}
}
Not mentioning logical errors in your code, you should probably create logical (boolean) variable outside of the loop and set it to false. If you encounter your condition, set it to true.
After the while loop, check the value. If it's false, that means no lines were found and you should print your message.
Example:
boolean foundAnything = false;
while(...) {
...
if(condition) {
foundAnything = true;
...
}
...
}
// Nothing was found
if(!foundAnything) {
...
}
sometimes it doesn't matter what i enter it always says "no match for your search"
The biggest issue here is this part inside your loop:
while(in.hasNext()) {
if(line.contains(search)) {
System.out.println(line);
}
if(!line.contains(search)) {
System.out.println("no match for your search");
//HERE!!!
System.exit(0);
}
}
System.exit(0) will stop the program and nothing else will be executed. So if the search word is not found in the line, the program finishes.
sometimes it says java.util.NoSuchElementException: No line found
You read the first line before the loop and maybe you have an empty file.
File file = new File("library.txt");
Scanner in = null;
in = new Scanner(file);
//this reads the first line of the file
String line = in.nextLine();
while(//rest of code...
You can overcome these two issues by:
Read the contents of the file only in the loop
Use a flag to check if the word was found
Stop the loop only if the word was found OR if the file has no more lines
In the loop, if the word is not found yet, just let it continue
Avoid using System#exit unless really needed
If after the loop the word was not found, print a message
With these suggestions in mind, your code can be designed like this:
File file = new File("library.txt");
Scanner in = new Scanner(file);
//Use a flag to check if the word was found
boolean found = false;
//Stop the loop only if the word was found OR if the file has no more lines
while (!found && in.hasNextLine()) {
//Read the contents of the file only in the loop
String line = in.nextLine();
if (line.contains(search)) {
found = true;
System.out.println(line);
}
//In the loop, if the word is not found yet, just let it continue
}
//If after the loop the word was not found, print a message
if (!found) {
System.out.println("no match for your search");
}
First of all you seem to skip your first line. Secondly, second if clause is redundant.
Boolean found=false;
while(in.hasNext()) {
String line = in.nextLine();
if(line.contains(search)) {
System.out.println(line);
found=true;
}
}
if(found==false) System.out.println("no match for your search");

Reading from a text file and changing the strings to int's to be entered in arrays is not working

Basically I am asking for the filename with a method called CS160Input (provided by my instructor) to ask for the filename. The text document has a bunch of entries each on their own lines, and I am trying to assign each number to a place in an array, but I am failing to actually write to the array. I know it is finding the file, because when i print out the counter, it tells me the correct amount of lines in the file. But when I try to print out a place in the array, I tried index 3 as you can see in my code, and it gives me 0 regardless of what I try. I tried creating an array of strings first and I ended up getting null for each index value as well.
public static void caclulate() throws FileNotFoundException {
String fileName = CS160Input.readString("Please enter the name of the file: ");
Scanner sc = new Scanner (new File (fileName));
int value, counter = 0;
int array[] = null;
while (sc.hasNextLine()) {
sc.nextLine();
counter++;
}
Scanner scanner = new Scanner(new File(fileName));
int[] calcArray = new int [counter];
int i = 0;
while(scanner.hasNextInt()){
calcArray[i++] = scanner.nextInt();
}
System.out.println(calcArray[3]);
System.out.println(counter);
}
Thanks to #Gendarme pointing out that hasNextInt() could be spitting out false if there were values in between, it made me take a closer look and I realized that in a previous program the numbers being written to the text file were doubles with 2 decimal places. Once I changed to hasNextDouble(), the program worked as intended.

How do I ask a user for a input file name, and then use that file name?

I am trying to ask the user for the name of their file, then I am going to scan the file to see how many indices are in the file, and then put it in an array and go from there.
Here is my code:
import java.util.*;
import java.io.*;
public class TestScoresAndSummaryStatistics {
public static void main(String[] args) throws IOException {
int scores;
int indices = -1;
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter the name of the file");
String fileName = keyboard.next();
//I believe something is wrong here, am I incorrectly bring inputFile into new File?
File inputFile = new File(fileName);
Scanner data = new Scanner(inputFile);
while (data.hasNext()) {
indices++;
}
System.out.println("There are: " + indices + "indices.");
}
}
I believe something went wrong with the = new File(filename); part: maybe because I didn't have quotes, but I'm not exactly sure. How can I fix this?
Solution:
Change
while (data.hasNext()) {
indices++;
}
to
while (data.hasNext()) {
indices++;
data.next();
}
Explanation:
You want to increment indices for every line. To achieve this, you should go to the next line and check if there are other available lines. Q: How can you go to the next line ? A: data.next();
E.g. - file.txt:
Your approach - bad:
Step 1
line a <--- here you are
line b
line c
Step 2
line a <--- here you are
line b
line c
...
data.hasNext() will be true forever because you will be on the first line at every step => infinite loop
Correct approach:
Step 1
line a <--- here you are
line b
line c
Step 2
line a
line b <--- here you are
line c
Step 3
line a
line b
line c <--- here you are
In this case data.hasNext() will return true only 3 times, then it will return false ( the file doesn't have any line after the 3rd line )
You only check if there is data in Scanner but you never consume it.
The java.util.Scanner.hasNext() method Returns true if this scanner has another token in its input. This method may block while waiting for input to scan. The scanner does not advance past any input.
The below code will never end if there is any data in file, you increase your counter with out reading the data.
while (data.hasNext()) {
indices++;
}

Categories

Resources