Why do I keep receiving an inputmismatchexception on my array? - java

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];`

Related

Reading data points from a data file

I have a data file with 1000 data points that is organized like this:
1000
16 11
221 25
234 112
348 102
451 456
I'm trying to read the file into my program and find an arrangement of the points that results in the shortest total point to point distance. Since I have little experience with lists, I'm having a lot of trouble even reading the data points. Is there a better way to go about this? How do you run the list through a nearest neighbor algorithm?
public static void main(String[] args) throws IOException {
File file = new File("output.txt");
Scanner scanner = new Scanner(file);
ArrayList<shortestRoute> arrayList = new ArrayList<shortestRoute>();
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
String[] fields = line.split(" ");
arrayList.add(new shortestRoute(Integer.parseInt(fields[0]), Integer.parseInt(fields[1])));
}
scanner.close();
System.out.println(arrayList);
}
I know that the formula for finding point to point distance is SquareRoot[(x2-x1)^2-(y2-y1)^2]. What I'm having trouble with is inputting the data points into the greedy algorithm.
You are splitting the input String using four spaces. Looking at the input file I assume that the numbers could also be separated by a tab. Rather using four spaces you should look for any white space. The split function should change like this:
String[] fields = line.split("\\s+");
I think it's because the first line is the number of points in the file.
Since it's all numbers just stick to using Scanner.
public static void main(String[] args) throws IOException {
File file = new File("output.txt");
Scanner scanner = new Scanner(file);
ArrayList<shortestRoute> arrayList = new ArrayList<shortestRoute>();
for(int i =0, n = scanner.nextInt(); i < n; i++) {
arrayList.add(new shortestRoute(scanner.nextInt(), scanner.nextInt()));
}
scanner.close();
System.out.println(arrayList);
}

How do I read a single text file and have the values placed into a cookie cutter sentence format?

Here's the content of the text file:
1 2 3 4 5 6 7 8 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
I want it to read and print out like this
The number ____ was at 00:00.
The number ____ was at 01:00.
and so on...
Here is what I have so far. I have found a lot about reading a .txt file but not much with how to take the info and format it in such a way.
One part of the code is for solving another objective which is to find the avg, min,, and max value. I just need help with the printing out the list format.
import java.io.File;
import java.io.IOException;
import java.util.Scanner;
public class NumberThingy {
public static void main(String[] args) throws IOException {
// Create new Scanner object to read from the keyboard
Scanner in = new Scanner(System.in);
//Ask human for file name
System.out.println("Please enter the name of your data file with it's extension i.e Whatever.txt: ");
String fileName = in.next();
// Access the file provided
Scanner fileToRead = new Scanner(new File(fileName));
double Sum = 0;
int NumberOfEntries = -1;
double HighestValue = 0, LowestValue = 0;
boolean StillRecording = true;
double CurrentValue;
while (fileToRead.hasNext()) {
if (fileToRead.hasNextDouble())
{
NumberOfEntries++;
CurrentValue = fileToRead.nextDouble();
if (StillRecording)
{
HighestValue = CurrentValue;
LowestValue = CurrentValue;
StillRecording = false;
}
else
{
HighestValue = Math.max(HighestValue,CurrentValue);
LowestValue = Math.min(LowestValue, CurrentValue);
}
Sum += CurrentValue;
}
else
{
fileToRead.next();
}
}
System.out.println("Here are your resutlts:");
System.out.println("Minimum Temp = " + LowestValue);
System.out.println("Maximum Temp = " + HighestValue);
System.out.println("Average Temp: " + Sum/NumberOfEntries);
System.out.println("There are " + NumberOfEntries + " temp recordings.");
System.out.println("It dipped down to 32 F " + FreezeCounter + " times.");
}
}
Thank you for your time and patience! I'm a student and love this community's enthusiasm.
It seems like you do have a lot of good things in place already, but as you are new to these concepts I'd recommend breaking this program into small working examples--little "aha" success moments.
For example, with the Scanner class, hard-code in the file location and simply get it to print the values from the file.
Scanner fileToRead = new Scanner(new File("c:\\hard-coded-file.txt"));
while (fileToRead.hasNext()) {
if (fileToRead.hasNextDouble())
{
System.out.println(fileToRead.nextDouble());
}
else
{
fileToRead.next();
}
}
Once you can do that, then add in your analysis logic. As of right now, it appears that your highest and lowest values will likely turn out to be the same value.
Lastly, consider reviewing the class and variable naming conventions for Java (you should do this for every language you work in) as, for example, standard variable names are written in camelCasing rather than PascalCasing as you have done.
EDIT/UPDATE
In regards to the cookie cutter format, I think you are on the correct track. To achieve what you are wanting, you will likely have to add a println statement within the while loop and print as you go, or you could experiment with something like a list of strings
LinkedList<String> outputStrings = new LinkedList<String>();
and adding the strings
outputStrings.add("The number ___ was at 00:00"));
to that list. You could then loop through the list at the end to print it all at once. Note that you may consider looking into String.format() to get leading zeroes on numbers.
Do you know about printf? Here is a cheatsheet I used when I was learning java.
https://www.cs.colostate.edu/~cs160/.Summer16/resources/Java_printf_method_quick_reference.pdf
System.out.printf("Today's special is %s!", "tacos");
Basically the method will replace whatever %s %f you have in the first string with the variables listed after the first string. It prints "Today's special is tacos!" You have to match the types right: %s is for string, %f for floating points.
Its all in the link.

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...*/
}

How to make an array from a text file

let me start off by saying that I am a fairly new Java programmer, and what I am trying to attempt is a bit over my head. Thus, I came here to try to learn it.
Okay, so here's the issue: I am trying to build a program that makes a 2d array from values in a text document. The text document has three columns and many rows (100+)...basically a [3][i] array.
Here's what I can do: I understand how to read the text file using bufferedReader. Here is a sample program I have that prints the text exactly how it looks in the text file (I apologize ahead for bad formatting; it's my first time on these forums):
import java.io.BufferedReader;
import java.io.FileReader;
public class Main {
public static void main(String[] args) throws Exception {
BufferedReader br = new BufferedReader(new FileReader("RA.txt"));
String line = null;
while ((line = br.readLine()) != null) {
String[] nums = line.split(",");
for (String str : nums) {
System.out.println(str);
}
}
br.close();
}
}
This is what is printed:
00 03 57.504
02 04 03.796
00 06 03.386
03 17 43.059
00 52 49.199
05 52 49.555
etc, etc.
Please help me in making an array with values. Thank you!
define a list outside your while loop like
List list = new LinkedList();
Inside your while loop, add the splitted array to the list, like
list.add(line.split(","));
After the while loop convert your list to an array, resulting in a 2D array:
Foo[] array = list.toArray(new Foo[list.size()]);

Java Array Index Out of Bound

I have the following code that reads through a line of students and the program should split at each white space then go to the next part of the text but I get arrayindexoutofBound exception.
The text file has several lines like this:
130002 Bob B2123 35 34 B2132 34 54 B2143 23 34
public static void main(String[] args) throws FileNotFoundException {
File f = new File("C:\\Users\\Softey\\Documents\\scores.txt");
Scanner sc = new Scanner(f);
List<MarkProcessing> people = new ArrayList<MarkProcessing>();
while(sc.hasNextLine()){
String line = sc.nextLine();
String[] details = line.split("\\s+");
String regNumber = details[0];
String name = details[1];
String modOne= details[2];
int courseM = Integer.parseInt(details[3]);
int examM = Integer.parseInt(details[4]);
String modTwo = details[5];
int courseM2 = Integer.parseInt(details[6]);
int examM2 = Integer.parseInt(details[7]);
String modThree = details[8];
int courseM3 = Integer.parseInt(details[9]);
int examM3= Integer.parseInt(details[10]);
MarkProcessing p = new MarkProcessing(regNumber, name, modOne,courseM, examM, modTwo,courseM2,examM2, modThree, courseM3, examM3);
people.add(p);
}
}
}
When it goes to details[1] I get the index error.
Without information regarding the input file, I am going to guess this is because of blank lines in your file. If this is the case, you should try something to ensure that you have enough pieces.. For this, your while loop could be something like this.
while(sc.hasNextLine()){
String line = sc.nextLine();
String[] details = line.split("\\s+");
if(details.length < 11) continue; // skip this iteration
...
}
Keep in mind this is only going to work if you are checking at least 11 items per line. If you need a more advanced method of parsing the input, whereas they may have any number of courses. You are better off thinking of another approach than simply storing values directly from indices.
You should try printing the line before parsing it so that you can see what causes it to blow up.
String line = sc.nextLine();
String[] details = line.split("\\s+");
String regNumber = details[0];
String name = details[1];
String modOne= details[2];
You are splitting on chunks of spaces. In the event you encounter a line with no spaces, then there will only be a single element and therefore details[1] will throw an IndexOutOfBoundsException.
My suggestion is to examine your input carefully. Does it have at trailing line feed? If so, that may be interpreted as a blank line
130002 Bob B2123 35 34 B2132 34 54 B2143 23 34
<blank line>
To split by space, you need to use:
String[] details = line.split(" "); // "\\s+" -> does not split by space.
In your case, it is trying to split the line by the regex pattern '//s+' and since this is not found, it considers the whole line to be one string. In this case, the size of the string array is 1. There is no details[1] and hence you get this error.

Categories

Resources