Getting No Such Element Exception Reading in file - java

I'm reviewing practice assignments working up to my final and one thing my professor had us do was create and use a student class. Below I provided my code and what's in the text file I'm reading from.
String inputFileName = "quizScore.txt";
File inputFile = new File(inputFileName);
Scanner fileIn = new Scanner(inputFile);
ArrayList<Student> students = new ArrayList<Student>();
//Skip first two lines
fileIn.nextLine();
fileIn.nextLine();
int i =0;
while (fileIn.hasNextLine()){
//skip first number
fileIn.nextInt();
//Add student with quiz score
String newStudent = fileIn.next();
int quizScore = fileIn.nextInt();
Student student = new Student(newStudent);
students.add(student);
//Add quiz score
student.addQuiz(quizScore);
i++;
}
Skip this line
And this line
1 Michael 285
2 Christopher 236
3 Joshua 230
4 Brandon 208
5 Jacob 202
6 Daniel 196
7 Matthew 193
8 Anthony 188
9 Andrew 172
10 Joseph 171
I wrote the class but when I try to implement the class its says NoSuchElementException in the while loop for the fileIn.nextInt(); that's suppose to skip the line number. I don't know why it's giving me that exception. If I do a print statement to see if there is an int there is. Which is why I'm confused I get an error.

Change the condition of the while loop to fileIn.hasNextInt(). That way, if your file has a new line at the end, your loop will stop when the next line does not start with an integer.
Also you don't seem to be using the value of your i variable anywhere. You may want to get rid of it, unused variables are never a good idea.

Related

Why do I keep receiving an inputmismatchexception on my array?

I have been running through this array of objects trying to figure out what I am doing wrong and I can't see the error. This program runs through the first iteration bringing in Austria and all its subsequent information but will not move onto the second part of the array. I thought it might be that it's somehow taking each variable from the countries class and making it its own spot in the array but that can't be it because I have increased the array size to 64 and it still stops at the end of Austria. I have been able to get it to go a bit further by placing print statements after each item is added and it seems to be adding an unaccounted for blank line in it for some reason and I'm not sure why. any help that could be given would be greatly appreciated.
This is my test code with the data list:
import java.util.Scanner;
import java.io.*;
public class Test {
public static void main (String [] args) throws IOException {
final String INPUT_FILE = "CountriesInfo2.txt";
FileReader inputDataFile = new FileReader (INPUT_FILE);
Scanner read = new Scanner (inputDataFile);
Countries[] c = new Countries[8];
for (int i = 0; i < c.length; i++) {
c[i] = new Countries();
c[i].countryName = read.nextLine();
c[i].latitude = read.nextLine();
c[i].longitude = read.nextLine();
c[i].countryArea = read.nextInt();
c[i].countryPopulation = read.nextInt();
c[i].countryGDP = read.nextDouble();
c[i].countryYear = read.nextInt();
sop ("" + c[i].countryName + "\n" + c[i].latitude+"\n"+c[i].longitude+"\n"+c[i].countryArea+"\n"+
c[i].countryPopulation+"\n"+c[i].countryGDP+"\n"+c[i].countryYear);
}// end for
} // End Main
public static void sop (String s) {
System.out.println(s);
} // End sop
} // end class
Austria
47 20 N
13 20 E
83871 8754513 417.2 2016
Belgium
50 50 N
04 00 E
30528 11491346 509.5 2016
Czech Republic
49 45 N
15 30 E
7886
10674723
350.7
2016
France
46 00 N
02 00 E
643801
67106161
2734.0
2016
This list is supposed to be one line for each bit of information with lat-long having 2 sets of double digits and a letter each.
nextLine() automatically moves the scanner down after returning the current line. Rather I would advise you do as following
read each line using String data = scanner.nextLine();
split the data using space separator String[] pieces =
data.split("\\s+");
set the pieces to Country attributes by converting them in to
their appropriate type.
eg. c[i].countryName = pieces[0];
`c[i].latitude = piece[1];`

How to read from text file, split strings from integers and then pass integers into an arraylist?

so I am very new to programming and have been trying out some exercises to better learn java.
Right now, I have a program that reads exam marks from a text file(contains only integers exclusively) and then passes that onto the arraylist.
Something like:
exammarks.txt file contains:
23 45 67 76 12
Scanner fileScan = new Scanner(new File("exammarks.txt");
ArrayList<Integer> marksArray = new ArrayList<Integer>();
while (fileScan.hasNextInt())
{
marksArray.add(fileScan.nextInt());
}
Print out: [23, 45, 67, 76, 12]
However I would like to modify this so that the exammarks.txt file contains:
name grade
NAME 56
NAME2 67
NAME3 43
and that the program reads this text file, ignores the first line, then splits the strings from the integers and then adds the integers onto the ArrayList.
Any help will be greatly appreciated
You can use your snippet and extend it to read the second .txt file aswell.
Your while loop now has to loop over lines.
fileScan.nextLine(); // skip first line
while (fileScan.hasNextLine())
{
marksArray.add(Integer.valueOf(fileScan.nextLine().split(" ")[1]));
}
So what happens here is that first you get the nextLine, split it by " " and get the second part where the Integer sits. But since nextLine returns a String which is split in two Strings you have to cast it to Integer or use the static method Integer.valueOf.

Token and line processing Java

I'm writing a program that reads data from a text file with various basketball sports statistics. Each line (after the two header lines) corresponds to one particular game and the scores of each team, with some other strings in there. I'm trying to use scanners to read the int scores of each game, store them in variables, and then compare them to determine which team won that game so that I can increment the wins later in the program. I figured out how to read all the ints in sequence, but I can't figure out how to read two ints in a line, store them as variables, compare them, and then move on to the next line/game.
Here is the relevant method:
public static void numGamesHTWon(String fileName)throws FileNotFoundException{
System.out.print("Number of games the home team won: ");
File statsFile = new File(fileName);
Scanner input1 = new Scanner(statsFile);
String line = input1.nextLine();
Scanner lineScan = new Scanner(line);
input1.nextLine();
input1.nextLine();
while (input1.hasNext()) {
if (input1.hasNextInt()) {
int x = input1.nextInt();
System.out.print(x);
input1.next();
} else {
input1.next();
}
}
A few lines from the text file:
NCAA Women's Basketball
2011 - 2012
2007-11-11 Rice 63 #Winthrop 54 O1
2007-11-11 #S Dakota St 93 UC Riverside 90 O2
2007-11-11 #Texas 92 Missouri St 55
2007-11-11 Tennessee 76 Chattanooga 56
2007-11-11 Mississippi St 76 Centenary 57
2007-11-11 ETSU 75 Delaware St 72 O1 Preseason NIT
read the file line by line. then split the line into a String[]. since you know where the scores are located on each line, you can then easily parse those values from the array and compare. can you please share a few lines form your input? then i can show you the exact code
you can try something like
String[] parts = str.split("\\D+");
where str is the line that you just read. now parts array will have all the numbers in your string. just read through the array, parse to int and make the comparison. note that the first three entries in this array would correspond to the date, so just ignore those.
for example
String[] parts = "2007-11-11 Mississippi St 76 Centenary 57".split("\\D+");
for (String g: parts)
System.out.println(g);
prints out
2007
11
11
76
57
so now you can just take the last two values and compare
while (input1.hasNextLine()) {
String line = input1.nextLine();
String[] parts = line .split("\\D+");
int score1 = Integer.parseInt(parts[parts.length-2]);
int score2 = Integer.parseInt(parts[parts.length-1]);
/*now compare score1 and score2 and do whatever...*/
}

Exception in java "java.util.InputMismatchException"

So, I am working on a code for class and can't figure what is wrong. The code compiles and when I enter the file I'm searching for, I get this message:
Enter the name of the file: FanData.txt
Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Scanner.java:909)
at java.util.Scanner.next(Scanner.java:1530)
at java.util.Scanner.nextInt(Scanner.java:2160)
at java.util.Scanner.nextInt(Scanner.java:2119)
at FanDriver.fillArray(FanDriver.java:76)
at FanDriver.main(FanDriver.java:35)
Press any key to continue . . .
I'm using TextPad as my compiler and the text file is in the project. The following is the code that I have written (ignore the methods being called in the quotes as they are something I need to do afterwards):
import java.io.*;
import java.util.Scanner;
public class FanDriver
{
private static Scanner keyboard = new Scanner(System.in);
public static void main(String args[]) throws IOException
{
// Constant for the amount of elements of the array
final int MAXSIZE = 100;
// Declaring variables
int amountFans = 0;
// Declaring and initializing our array of fans
Fan[] fans = new Fan[MAXSIZE];
// Calling all of our methods
amountFans = fillArray(fans, MAXSIZE);
/**
listFanData(fans, amountFans);
bubbleSortByAge(fans, amountFans);
listFanData(fans, amountFans);
bubbleSortByFan(fans, amountFans);
listFanData(fans, amountFans);
searchByAge(fans, amountFans);
searchByFan(fans, amountFans);
*/
}
public static int fillArray(Fan[] array, int MAXSIZE) throws IOException
{
// Declaring variables
int counter = 0;
int age;
String name;
// Getting the file name
System.out.print("\nEnter the name of the file: ");
String fileName = keyboard.nextLine();
// Opening the file
File file = new File(fileName);
Scanner inputFile = new Scanner(file);
// Making sure the file was successfully opened
if (!file.exists())
{
System.out.println("\nERROR: FILE DOESN'T EXIST. CLOSING PROGRAM NOW.");
// Exiting the program
System.exit(0);
}
// Reading all of the amounts from the file
while (inputFile.hasNext() && counter < MAXSIZE)
{
name = inputFile.nextLine();
age = inputFile.nextInt();
array[counter] = new Fan(name, age);
// Adding to our counter
counter = counter + 1;
}
//Closing file
inputFile.close();
return counter;
}
}
I do not have the code for the Fan class, just the class itself.
The file we are retrieving is the file FanData.txt, which looks like this:
Chris P. Cream
5
Scott Free
9
Lou Tenant
3
Trish Fish
12
Ella Mentry
4
Holly Day
3
Robyn DeCradle
12
Annette Funicello
4
Elmo
7
Grover
3
Big Bird
9
Bert
7
Ernie
3
Grover
9
The text file is line-by-line. One line is a name and the next is a number. I don't know how to format it correctly on here.
Any help would be greatly appreciated.
I am not sure about the delimiter in your input file.
The way you had instantiated your "Scanner"(without specifying any explicit delimiter) shall use default delimiter i.e. a whitespace character.
It seems that the "nextLine()" method in your case is not returning a "line".
It is rather returning a number or string(may be, you need check your file for that) which is not matching with the pattern followed by your Scanner.
The error is because of the type mismatch. After your first read scanner will be pointing to a non Integer value.
try to print your name before doing
age = inputFile.nextInt();
you will get to know the issue.
Above mentioned are means to understand the mistake.
Solution for your problem
Try :
age = Integer.parseInt(inputFile.nextLine()); // instead of age = inputFile.nextInt();
Exception is because of type mismatch as you are reading a text value from textfile and directly assigning to an int type.
Exception will be resolved if you parse the value as an integer as below
Integer.valueOf(inputFile.nextLine());

File Read, printing on a single line

Why does it print the file it reads on a single line? The txt file is not.
The file is like this:
Student N. 3
ID: 999
Surname: Spider
Name: Man
************
Subject N. 1 : d. Chart Reading
Homework 1: 89
Homework 2: 65
Homework 3: 32
Exam 1: 45
Exam 2: 56
Exam 3: 78
public static void main(String[] args) throws Exception {
Scanner data = new Scanner(new FileReader("StudData1.txt"));
while(data.hasNextLine())
{
System.out.print(data.nextLine());
}
Change System.out.print() to System.out.println() if you want to print in different line.
You should know the difference between these two. Follow this link.

Categories

Resources