Token and line processing Java - 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...*/
}

Related

Getting No Such Element Exception Reading in file

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.

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.

Collections.frequency not working correctly in Android

I have a code in my android phone to find duplicate numbers via collections.frequency. This code works fine in a java program only on android. But not as an app on android. Here is what I have as a code in android.
ArrayList<String> ll = new ArrayList<String>();
String item = inputText.getText().toString();
ll.add(item);
HashSet<String> set = new HashSet<>(ll);
for (String temp : set)
{
answertext.setText(temp + "shows that many times: " + Collections.frequency(ll, temp));
}
The output is as follows:
33 44 33 44 shows that many times: 1
It does not find any duplicates if the numbers are input by user via textbox.
However, if a take the userinput away in the code and replace it with this input:
ll.add("33");
ll.add("44");
ll.add("33");
ll.add("44");
ll.add("24");
ll.add("24");
the output will be like so:
44 shows that many times: 2
So here with this input the collections.frequency is working to find a duplicate number. But why only one number? And why 44 and not 33? And why is it not outputting all duplicate numbers like it does as a java program only on the phone. Without Android involved?
I'd like to make it work with userinput from a textbox.
On the Java side where it works fine I got this code:
List<String> list = new ArrayList<String>();
Scanner stdin = new Scanner(System.in);
System.out.println("Enter the amount of numbers you want to input: Input numbers separated by a space.");
int n = stdin.nextInt();
for (int i = 0; i < n; i++)
{
list.add(stdin.next());
}
System.out.println("\nCount all with frequency");
Set<String> uniqueSet = new HashSet<String>(list);
for (String temp : uniqueSet)
{
System.out.println(temp + " shows that many times : " + Collections.frequency(list, temp));
}
//Enter the amount of numbers you want to input
12 //hit the return key
22 33 44 22 33 44 22 33 44 22 33 44
//the output is like so:
Count all with frequency
33 shows that many times: 4
44 shows that many times: 4
22 shows that many times: 4
Why is this code working in Java but not on android?
String item = inputText.getText().toString();
ll.add(item);
This adds one item to the list. I'm guessing you wanted to add each word separately, which you can do like this:
// split the input apart at the spaces
String[] items = inputText.getText().toString().split(" ");
// then add each part separately to the list
for(String item : items)
ll.add(item);
Your second problem is that setText... sets the text. It doesn't add to the end of the text, it replaces what's already there. I don't know how you intended to display multiple strings, but you could do something like this:
// clear answertext
answertext.setText("");
for (String temp : set)
{
// set the text to <whatever was already there> followed by this item
answertext.setText(answertext.getText() + temp + "shows that many times: " + Collections.frequency(ll, temp) + "\n");
}

Save multiple strings into one string

I want to save multiple strings in one. Thing is, I don't know how many strings it may be.
I'm creating a program that reads calories from a text file and stores them in corresponding arrays.
Here are parts of the text:
Description of food Fat Food Energy Carbohydrate Protein Cholesterol Weight Saturated Fat
(Grams) (calories) (Grams) (Grams) (Milligrams) (Grams) (Grams)
APPLES, RAW, PEELED, SLICED 1 CUP 0 65 16 0 0 110 0.1
APPLES, RAW, UNPEELED,2 PER LB1 APPLE 1 125 32 0 0 212 0.1
APPLES, RAW, UNPEELED,3 PER LB1 APPLE 0 80 21 0 0 138 0.1
APRICOT NECTAR, NO ADDED VIT C1 CUP 0 140 36 1 0 251 0
Now for the food name, I have an array foodName. I will read the whole string until I reach an int which is the amount.
Here is what I've done so far:
Scanner input = new Scanner("Calories.txt");
while (input.hasNext()) {
String[] words = input.next().split(" ");
int lastI;
for (int i=0; i < words.length; i++) {
if (isNumeric(words[i])) {
lastI = i;
for(int j=lastI; j>=0; j++){
//What should I put here?
}
}
}
}
public static boolean isNumeric(String str) {
try {
double d = Double.parseDouble(str);
} catch (NumberFormatException nfe) {
return false;
}
return true;
}
for the inner most for loop, I kept track of the last index so I could start from it and go backwards.
Problem 1: If I go backwards in the second line, I will copy both lines.
Problem 2: How to save all the strings of the name in one index of foodName?
All help is appreciated :)
What you are looking for in Java is called a StringBuilder. You can use this essentially like a string and keep appending onto it.
File file = new File("output.txt");
Scanner input = new Scanner(file);
StringBuilder sb = new StringBuilder();
while (input.hasNextLine()) {
String[] words = input.nextLine().split(" ");
for (int i = 0; i < words.length; i++) {
if (isNumeric(words[i])) {
break;
}
sb.append(words[i] + " ");
}
System.out.println(sb);
sb = new StringBuilder();
}
input.close();
What this does is read the file line by line, creating an array of strings splitting the line on " ". Then, it iterates over each of the strings in the array and checks if it is a number, if it is, it will break the current loop and move onto the next line.
I had the StringBuilder print after each line, and then reset, you should replace this with whatever functionality that you want.
A couples suggestions also for you:
Use a CSV file. Separate everything with commas instead of spaces, it makes parsing extremely easy.
Use regex to check if the string is a number instead of catching exceptions, it is more elegant.
The output of this comes out a little funny because of how you formatted your file. You are parsing on " ", but you added a bunch of extra " " characters in the file to make the format look nice. This messes up your parsing very badly. BUT, this method will parse for you correctly when you fix the format of your flat file.
Output from this was: (note that each line is a separate string. You can see how the file formatting messed up the output)
Description of food Fat Food Energy Carbohydrate Protein Cholesterol Weight Saturated Fat
(Grams) (calories) (Grams) (Grams) (Milligrams) (Grams) (Grams)
APPLES, RAW, PEELED, SLICED
APPLES, RAW, UNPEELED,2 PER LB1 APPLE
APPLES, RAW, UNPEELED,3 PER LB1 APPLE
APRICOT NECTAR, NO ADDED VIT C1 CUP

Categories

Resources