Floating Decimal, Parsing info from fileread- what is going on - java

okay guys im really really confused and all or any help is appropriated to the MAX!
EDIT: I am working on an assignment that deals with reading data from a text file, and parsing that data to various arrays. i am stuck on parsing, keep receiving a floating decimal error.
This is my first time ever using fileread. im trying to extract the hours and wage from employees and calculate their gross and net pay. Then i wanted to display, in alphabetical order, a managers report of all their information plus my calculated information...
i have efficiently wrote a program that displays their information. i cannot, for the life of me, find a way to parse this information to start applying my calculations. first let me show you what i have, then i will show you what i am doing and the results.
here is what i have:
import java.awt.HeadlessException;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import javax.swing.JFrame;
import javax.swing.JLabel;
public class T2 {
public static void main(String[] args)
{
String list = "";//creates a list for output GUI
System.out.println("Reading File ......");
//Name of the file with precise directory
//String fileName="data.txt"
String fileName="G:\\cs215\\assign 2\\FileRead\\READTHIS.txt"; //turns a file into string
//tring fileName="C:\\cs130\\Max_names.txt"; //turns a file into string on my PC
//Arrays to store variables for each person
String [] extra = new String [11];
String [] Name = new String [11];
String [] familyName = new String [11];
String [] FName = new String [11];
String [] credit = new String [11];
String [] hr = new String [11];
String [] wg = new String [11];
Double [] wage = new Double [11];
Double [] hrworked = new Double [11];
try{//Try tests the code inside of it for errors.
//Create object of FileReader
FileReader inputFile = new FileReader(fileName);
//Instantiate the BufferedReader Class
BufferedReader bufferReader = new BufferedReader(inputFile);
//Variable to hold the one line data
String line = null;
// Read file line by line and print on the console
int row = 0;
while ((line = bufferReader.readLine()) != null) {
extra[row]= line;
row++;
}
//Close the buffer reader
bufferReader.close();
//This loop contains and seperates each line into individual words
for (int y = 0;y<=9;y++)
{
//seperates the first word in each line from the other ones.
int u = 0;
while(u < extra[y].length())
{
if(extra[y].charAt(u) == ',')//Determines the point at which the words are seperated
{
//Splits one word and the remaining words into two variables
Name[y] = extra[y].substring(0, u);
familyName[y] = extra[y].substring(u + 1, extra[y].length());
u = extra[y].length();
}
++u;
}
//seperates the second word in each line from the other ones.
int a = 0;
while(a < familyName[y].length())
{
if(familyName[y].charAt(a) == ',')//Determines the point at which the words are seperated
{
//Splits one word and the remaining words into two variables
FName[y] = familyName[y].substring(0, a);
credit[y] = familyName[y].substring(a + 1, familyName[y].length());
a = familyName[y].length();
}
++a;
}
//Puts the words back together in re-sorted order
extra[y] = ("" +FName[y] +", "+Name[y]+", " +credit[y]+ "");
}//end of sorting and resorting loop
//places each name in string.
String[] arr = {extra[0], extra[1], extra[2], extra[3],extra[4], extra[5], extra[6], extra[7], extra[8], extra[9]};
//rearanges the string in alphabetical order from top to bottom based on last name
String tmp;
for (int i = 0;i < arr.length;i++)
{
tmp = arr[i];
for (int j = 0;j < arr.length;j++)
{
if (i == j) continue;
int x = tmp.compareTo(arr[j]);
if (x < 0)
{
tmp = arr[j];
arr[j] = arr[i];
arr[i] = tmp;
}
}
}
//acquires the current date
DateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy");
Calendar cal = Calendar.getInstance();
for (int r=0;r<10;r++)
{
int pl = 0;
while(pl < arr[r].length())
{
if(arr[r].charAt(pl) == ',')//Determines the point at which the words are seperated
{
//Splits one word and the remaining words into two variables
familyName[r] = arr[r].substring(0, pl);
Name[r] = arr[r].substring(pl + 1, arr[r].length());
pl = arr[r].length();
}
++pl;
}
//seperates the second word in each line from the other ones.
int pr = 0;
while(pr < Name[r].length())
{
if(Name[r].charAt(pr) == ',')//Determines the point at which the words are seperated
{
//Splits one word and the remaining words into two variables
FName[r] = Name[r].substring(0, pr);
credit[r] = Name[r].substring(pr + 1, Name[r].length());
pr = Name[r].length();
}
++pr;
}
//Seperates the last two words in each line
int pz = 0;
while(pz < credit[r].length())
{
if(credit[r].charAt(pz) == ',')//Determines the point at which the words are seperated
{
//Splits one word and the remaining words into two variables
hr[r] = credit[r].substring(0, pz);
wg[r] = credit[r].substring(pz + 1, credit[r].length());
pz = credit[r].length();
}
++pz;
}}
//HERE IS WHERE I AM TRYING TO PARSE THE HOURS AND WAGE FROM MY DOC
//Prompts the JPanel
JLabel tran = new JLabel("Date: " + dateFormat.format(cal.getTime()) + "");
JFrame app = new JFrame("Manager Report");
app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Places all the variables in their correct spots
tran.setBounds(0, 10, 200, 20); // x, y, width, height x across, y down
JLabel tlast = new JLabel("Last Name:");
tlast.setBounds(0, 30, 200, 20);
JLabel tfirst = new JLabel("First Name:");
tfirst.setBounds(200, 30, 200, 20);
JLabel thour = new JLabel("Work hours:");
thour.setBounds(400, 30, 200, 20);
JLabel twage = new JLabel("Wage:");
twage.setBounds(600, 30, 200, 20);
JLabel Fix = new JLabel("");//This was added to make JPanel stop glitching
Fix.setBounds(1400, 30, 200, 20);
/*Goes throughthe list of people and places all the variables in their
correct spots. Note that each line output is lower than before.
*/
for (int t=0; t<=9;t++)
{
JLabel displaylname = new JLabel(""+familyName[t] +"");
displaylname.setBounds(0, 50+(20*t), 200, 20);
JLabel displayfname = new JLabel(""+FName[t]+"");
displayfname.setBounds(200, 50+(20*t), 200, 20);
JLabel displayhours = new JLabel(""+hr[t]+"hrs");
displayhours.setBounds(400, 50+(20*t), 200, 20);
JLabel displaywage = new JLabel(""+wg[t]+"$ per hr");
displaywage.setBounds(600, 50+(20*t), 200, 20);
//The required windows that allow output in the loop
app.add(displaylname);
app.add(displayfname);
app.add(displayhours);
app.add(displaywage);
}
//The required windows that allow output
app.add(tran);
app.add(tlast);
app.add(tfirst);
app.add(thour);
app.add(twage);
app.add(Fix);
app.setSize(800, 300);
app.setVisible(true);
//window.setLayout(null);
app.setResizable(false);
}//End of try
//catches the program, terminates it, and sends an error message if an error is encountered
catch(IOException | HeadlessException e){
System.out.println("Error while reading file line by line:" + e.getMessage());
}
}
}
the text doc im extracting from looks like this, firstname,last,hours,wage:
Sukken,Dey,45.0,75
Will,Duke,40,80
Adam,Kauffman,43,72
Shaun,Milson,40,65
Daniel,Jamestone,35,60
Matthew,Olberg,40,72
Andrew,Johnson,45,75
Arron,Winsen,42,70
Eric,Winsen,40,65
Mark,Dinger,45,75
im trying to parse the information into the double arrays i have defined at the top. I'm implementing these lines of code right before my promps for jpanel. i commented where.
for(int m=0; m<11; m++)
{
hrworked[m]=Double.parseDouble(hr[m]);
wage[m]=Double.parseDouble(wg[m]);
System.out.println(wage[m]);
}
i even placed a print line statement to see if the parses are working and it seems like they are until they hit an error. the output results in
run:
Reading File ......
75.0
Exception in thread "main" java.lang.NullPointerException
75.0
80.0
60.0
75.0
72.0
65.0
72.0
70.0
65.0
at sun.misc.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:1838)
at sun.misc.FloatingDecimal.parseDouble(FloatingDecimal.java:110)
at java.lang.Double.parseDouble(Double.java:538)
at t2.T2.main(T2.java:147)
C:\Users\Adamska\AppData\Local\NetBeans\Cache\8.1\executor-snippets\run.xml:53: Java returned: 1
BUILD FAILED (total time: 0 seconds)
it appears to be parsing because it prints out values for each line but it results in an error and im not sure what the cause is. is this an appropriate approach or should i be using something else to parse my values? if someone could explain what is going on and point me in what i need to do id greatly appreciate it

Related

Read the data from the file and store it in two arrays

hello I am having trouble with trying to read a file and take the two columns of the file and put them respectively in their own arrays. Any help would be appreciated! Thanks!
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
// TODO Auto-generated method stub
System.out.println("Please enter the name of the file to be read");
String fileName = keyboard.nextLine();
Scanner chirping = null;//user input for file name
boolean fileValue = false; //this makes the value false until the correct file name is inputed
while(!fileValue) {
try {
FileReader dates = new FileReader(fileName); // connects to the user inputted file
chirping = new Scanner(dates); //scans the file
fileValue = true; //turns file value to true which takes us out of the while loop
}//end try
catch(IOException e) {
System.out.println("File Not Found, Please Try Again: ");
fileName = keyboard.nextLine();
}//end catch
}// end while
double[] dataSet = new double[30];
double[] chirpFreq = new double[30];
double[] temp = new double[30];
//double[] temp = new double[chirping.nextInt()];
for(int i = 0; chirping.hasNextDouble(); i++) {
dataSet[i] = chirping.nextDouble();
}
for(int j = 0; j <= dataSet.length; j++) {
if(j%2 == 0) {
chirpFreq[j] = dataSet[j];
}
else {
temp[j] = dataSet[j];
}
}
for(int i = 0; i <= chirpFreq.length; i++) {
System.out.print(chirpFreq[i]+ " ");
}
chirping.close();
}
//These are the values i am trying to sort into two separate arrays
20 88.6
16 71.6
19.8 93.3
18.4 84.3
17.1 80.6
15.5 75.2
14.7 69.7
17.1 82
15.4 69.4
16.2 83.3
15 79.6
17.2 82.6
16 80.6
17 83.5
14.4 76.3
I don't usually use nextDouble() to read files so i don't know what your problem is exactly, but you can refactor your code to this:
double[] firstColumn = new double[30];
double[] secondColumn = new double[30];
String line = "";
int i = 0;
// keep reading until there is nothing to read
while( (line = chirping.nextLine()) != null ) {
// this is a regex that splits the line into an array based on whitespace
// just use " " if your data is separated by space or "\t" if tab
String[] columns = line.split("\\s+");
firstColumn[i] = Double.parseDouble(columns[0]);
secondColumn[i++] = Double.parseDouble(columns[1]);
}
chirping.close();

Is it possible to write a text file in such a way that when read by the Java compiler, it will add a line break at certain points?

For my Java class, I'm working on a project that is essentially a database for MTG cards. I have to read from a file as part of the project, so I am reading the card information from a file, and then splitting the lines to put each different type of information together to form different object classes for the different types of cards. The main nitpicky issue I'm running into right now is that I need the card text to be on one line in the text file so I can read it line by line, but I'd prefer if it weren't all on one line when I print it to the console. Is there any way to add a character combination into the text of the file itself that will tell my compiler, "line break here," when it reads that, or am I out of luck? I know I could just use \n in the code to achieve this, but as I am looping through the file, there is no way to do so properly that I know of, as not every card's text needs line breaks inserted. If it matters, this is the chunk of my code that deals with that:
import java.io.BufferedReader;
import java.io.FileReader;
import java.util.Scanner;
public class MTG {
public static void main(String[] args) {
int creatureLength = 4;
//Prompt User
Scanner sc = new Scanner(System.in);
System.out.println("Welcome to the Magic: the Gathering card database. This tool currently supports Rare and Mythic Rare cards from the Throne of Eldraine Expansion.");
try {
System.out.println("\nSelect the card type you'd like to view.");
System.out.println(""
+ "(1)Creatures\n"
);
int choice = Integer.parseInt(sc.next());
//Choose type
//Creatures
if(choice == 1){
Creature[] creatures = creatureGen("textfiles/Creatures.txt", creatureLength);
System.out.println("\nViewing creatures. Which card would you like to view?: \n");
for(int k = 0; k < creatureLength; k++) {
System.out.println(
"(" + (k + 1) + ") " + creatures[k].getName());
}
int creatureChoice = Integer.parseInt(sc.next());
try {
System.out.println("\n" + creatures[(creatureChoice - 1)]);}
catch(Exception e) {
System.out.println("Input was not a specified number. Exiting...");
}
}
}
catch(NumberFormatException ex){
System.out.println("Input was not a specified number. Exiting...");
}
sc.close();
}
//Read Creature text file
public static Creature[] creatureGen(String path, int length) {
Creature[] creatures = new Creature[length];
try {
FileReader file = new FileReader(path);
BufferedReader reader = new BufferedReader(file);
String name[] = new String[length];
String cost[] = new String[length];
String color[] = new String[length];
String type[] = new String[length];
String cTypes[] = new String[length];
String tags[] = new String[length];
String text[] = new String[length];
int power[] = new int[length];
int toughness[] = new int[length];
for (int i = 0; i < length; i++) {
String line = reader.readLine();
if(line != null) {
name[i] = line.split("\\|")[0];
cost[i] = line.split("\\|")[1];
color[i] = line.split("\\|")[2];
type[i] = line.split("\\|")[3];
cTypes[i] = line.split("\\|")[4];
tags[i] = line.split("\\|")[5];
text[i] = line.split("\\|")[6];
power[i] = Integer.parseInt(line.split("\\|")[7]);
toughness[i] = Integer.parseInt(line.split("\\|")[8]);
creatures[i] = new Creature(name[i], cost[i], color[i], type[i], cTypes[i], tags[i], text[i], power[i], toughness[i]);
}
}
reader.close();
}
catch (Exception e) {
System.out.println("Error reading file: " + path);
}
return creatures;
}
}
The Creature object class essentially just stores the data that I am putting into it with the creatureGen method. A sample line from the text file I am reading from looks something like this:
Charming Prince|1W|White|Creature|Human Noble||When Charming Prince enters the battlefield, choose one — • Scry 2. • You gain 3 life. • Exile another target creature you own. Return it to the battlefield under your control at the beginning of the next end step.|2|2
It would be ideal to be able to insert line breaks after each of the bullet points in this card, for example, but as I said earlier, I need the text to be in one line for my loop to read it. Is there any way around this when I print this back to the console? I appreciate any help.
Just replace those bullet points with line breaks :
text[i] = line.split("\\|")[6].replaceAll("•","\n");
Also, you should not split each time you need an element, put the result of line.split("\|") in a String[] variable and use it afterwards.
for (int i = 0; i < length; i++) {
String line = reader.readLine();
if(line != null) {
String[] elements = line.split("\\|");
name[i] = elements[0];
cost[i] = elements[1];
color[i] = elements[2];
type[i] = elements3];
cTypes[i] = elements[4];
tags[i] = elements[5];
text[i] = elements[6].replaceAll("•","\n");
power[i] = Integer.parseInt(elements[7]);
toughness[i] = Integer.parseInt(elements[8]);
creatures[i] = new Creature(name[i], cost[i], color[i], type[i], cTypes[i], tags[i], text[i], power[i], toughness[i]);
}
}
Finally, about vocabulary, the compiler is not reading your file. The compiler translates your code into binary instructions for the processor (to summarize).
Your file is read at runtime.

how to link a main class to a jframe form in java using netbeans

Good day!
I have created a code using Netbeans and it executes the processes just fine.
Now, i want my input to given and output to be displayed through a user interface. I have then created a 2 Jframes, 1 to collect the user's input and the other to display the results after execution by the code.
But, i am unable to link the interface to the main class(called NgramBetaE) as i am not aware of how i can do so.
I highly welcome suggestions.
The main class in its entirety is;
package ngrambetae;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.*;
/**
*
* #author 201102144
*/
public class NgramBetaE {
static LinkedList<String> allWords = new LinkedList<String>();
static LinkedList<String> distinctWords = new LinkedList<String>();
static String[] hashmapWord = null;
static int wordCount;
public static HashMap<String,HashMap<String, Integer>> hashmap = new HashMap<>();
public static HashMap<String,HashMap<String, Integer>> bigramMap = new HashMap<>();
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
//prompt user input
Scanner input = new Scanner(System.in);
//read words from collected corpus; a number of .txt files
File directory = new File("Corpus");
File[] listOfFiles = directory.listFiles();//To read from all listed iles in the "directory"
int lineNumber = 0;
String line;
String files;
String delimiters = "[()?!:;,.\\s]+";
//reading from a list of text files
for (File file : listOfFiles) {
if (file.isFile()) {
files = file.getName();
try {
if (files.endsWith(".txt") || files.endsWith(".TXT")) { //ensures a file being read is a text file
BufferedReader br = new BufferedReader(new FileReader(file));
while ((line = br.readLine()) != null) {
line = line.toLowerCase();
hashmapWord = line.split(delimiters);
//CALCULATING UNIGRAMS
for(int s = 0; s < hashmapWord.length; s++){
String read = hashmapWord[s];
allWords.add(read);
//count the total number of words in all the text files combined
//TEST
wordCount = 0;
for (int i = 0; i < allWords.size(); i++){
wordCount ++;
}
}
//CALCULATING BIGRAM FREQUENCIES
for(int s = 0; s < hashmapWord.length -1; s++){
String read = hashmapWord[s];
final String read1 = hashmapWord[s + 1];
HashMap<String, Integer> counter = bigramMap.get(read);
if (null == counter) {
counter = new HashMap<String, Integer>();
bigramMap.put(read, counter);
}
Integer count = counter.get(read1);
counter.put(read1, count == null ? 1 : count + 1);
}
//CALCULATING TRIGRAM FREQUENCIES
for(int s = 0; s < hashmapWord.length - 2; s++){
String read = hashmapWord[s];
String read1 = hashmapWord[s + 1];
final String read2 = hashmapWord[s + 2];
String readTrigrams = read + " " + read1;
HashMap<String, Integer> counter = hashmap.get(readTrigrams);
if (null == counter) {
counter = new HashMap<String, Integer>();
hashmap.put(readTrigrams, counter);
}
Integer count = counter.get(read2);
counter.put(read2, count == null ? 1 : count + 1);
}
}
br.close();
}
} catch (NullPointerException | IOException e) {
e.printStackTrace();
System.out.println("Unable to read files: " + e);
}
}
}
//COMPUTING THE TOTAL NUMBER OF WORDS FROM ALL THE TEXT FILES COMBINED
System.out.println("THE TOTAL NUMBER OF WORDS IN COLLECTED CORPUS IS : \t" + wordCount + "\n");
for(int i = 0, size = allWords.size(); i < size; i++){
String distinctWord = allWords.get(i);
//adding a word into the 'distinctWords' list if it doesn't already occur
if(!distinctWords.contains(distinctWord)){
distinctWords.add(distinctWord);
}
}
//PRINTING THE DISTINCT WORDS
System.out.println("THE DISTINCT WORDS IN TOTAL ARE :\t " + distinctWords.size() + "\n");
System.out.println("PRINTING CONTENTS OF THE BIGRAMS HASHMAP... ");
System.out.println(bigramMap);
System.out.println("================================================================================================================================================================================================================================================================================================================\n");
System.out.println("PRINTING CONTENTS OF THE TRIGRAMS HASHMAP... ");
System.out.println(hashmap);
System.out.println("================================================================================================================================================================================================================================================================================================================\n");
//QUITTING APPLICATION
String userInput = null;
while(true) {
System.out.println("\n**********************************************************************************************************************************************************************************************************************************");
System.out.println("\n\n\t\tPLEASE ENTER A WORD OR PHRASE YOU WOULD LIKE A PREDICTION OF THE NEXT WORD FROM:");
System.out.println("\t\t\t\t(OR TYPE IN 'Q' OR 'q' TO QUIT)");
userInput = input.nextLine();
if (userInput.equalsIgnoreCase("Q")) break;
//FORMAT USER INPUT
String[] users = userInput.toLowerCase().split("[?!,.\\s]+");
if (users.length < 2) {
userInput = users[0];
//System.out.println("\nENTRY '" + userInput + "' IS TOO SHORT TO PREDICT NEXT WORD. PLEASE ENTER 2 OR MORE WORDS");
//CALCULATING BIGRAM PROBABILITY
int sum = 0;
try {
for(String s : bigramMap.get(userInput).keySet()) {
sum += bigramMap.get(userInput).get(s);
}
String stringHolder = null;
double numHolder = 0.0;
for(String s : bigramMap.get(userInput).keySet()) {
//System.out.println("TWO");
double x = Math.round(bigramMap.get(userInput).put(s, bigramMap.get(userInput).get(s))/ (double)sum *100 );
if(s != null){
if(numHolder < x ){
stringHolder = s;
numHolder = x;
}
}
}
System.out.println("\nNEXT WORD PREDICTED IS '" + stringHolder + "'");
System.out.println("ITS PROBABILITY OF OCCURRENCE IS " + numHolder + "%");
} catch (Exception NullPointerException) {
System.out.println("\nSORRY. MATCH NOT FOUND.");
}
} else {
userInput = users[users.length - 2] + " " + users[users.length - 1];
// System.out.println("FROM USER WE GET....");
// System.out.println(bigrams.get(userInput).keySet());
/* CALCULATING TRIGRAM PROBABILITY*/
int sum = 0;
try {
for(String s : hashmap.get(userInput).keySet()) {
sum += hashmap.get(userInput).get(s);
}
String stringHolder = null;
double numHolder = 0.0;
for(String s : hashmap.get(userInput).keySet()) {
//System.out.println("TWO");
double x = Math.round(hashmap.get(userInput).put(s, hashmap.get(userInput).get(s))/ (double)sum *100 );
if(s != null){
if(numHolder < x ){
stringHolder = s;
numHolder = x;
}
}
}
System.out.println("\nNEXT WORD PREDICTED IS '" + stringHolder + "'");
System.out.println("ITS PROBABILITY OF OCCURRENCE IS " + numHolder + "%");
} catch (Exception NullPointerException) {
System.out.println("\nSORRY. MATCH NOT FOUND.");
}
}
}
input.close();
}
}
My first Jframe which i would like to appear upon running the project has got a single textbox and a single button;
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
String usersInput = jTextField1.getText();
Interface1 s = new Interface1();
s.setVisible(true);
dispose();
}
i would like for the user to enter data in the textbox and when they click on the button 'predict next word' then the output from the code execution is displayed on the second jframe which has got 3 labels and relative text areas.
NOTE; i couldn't paste the screenshots but if you run the NgramBetaE class you will get an idea of how the interfaces will be as i tried to explain them.
Thank you
Don't even try to link your GUI code to your NgramBetaE code as you've more work to do since the NgramBetaE is little more than one huge static main method that gets user input from the console with a Scanner and outputs to the console via printlns. Melding these two is like trying to put a square peg into a round hole.
Instead re-write the whole thing with an eye towards object-oriented coding, including creation of an OOP-compliant model class with instance fields and methods, and a single GUI that gets the input and displays it, that holds an instance of the model class and that calls instance methods on this instance.
Consider creating non-GUI classes and methods for --
Reading in data from your text files
Analyzing and hashing the data held in the text files including calculating word frequencies etc...
Returning needed data after analysis in whatever data form it may be needed.
A method for allowing input of a String/phrase for testing, with return its predicted probability
Then create GUI code for:
Getting selected text file from the user. A JFileChooser and supporting code works well here.
Button to start analysis
JTextField to allow entering of phrase
JTextArea or perhaps JTable to display results of analysis
Note that you should avoid having more than one JFrame in your GUI. For more on this, please have a look at The Use of Multiple JFrames, Good/Bad Practice?

Substring - StringIndexOutOfBounds exception java

I've been working on a program to collect data from a file and do some stuff to it (as evident in the code and pseudocode) however I'm having difficulty getting each element of the string into the right array. A line from a file looks like this:
1980 Aug 945 100 Allen
I'm wanting to use the substring method because that'd be the easiest in my opinion. Is there a better way of doing it? Here's my code thus far. Where does the problem lie exactly, and how should I fix it? Thanks! :)
import java.util.Scanner;
import java.io.File;
import java.io.IOException;
import java.lang.String;
public class Hurricanes2
{
public static void main(String [] args) throws IOException
{
int counter = 0;
String [] token = new String[1000];
String [] tokenElements = new String[128];
String [] hurricaneYear = new String[64];
String [] hurricaneName = new String[64];
String [] hurricaneMonth = new String[64];
int [] hurricaneCategory = new int[64];
double [] hurricanePressure = new double[64];
double tempKnots;
double knotsToMph;
double [] hurricaneWindSpeed = new double[64];
double categoryAverage;
double pressureAverage;
double speedAverage;
String headerData = " Hurricanes 1980 - 2006\n\n Year Hurricane Category Pressure(MB) Wind Speed (MPH)\n========================================================================";
Scanner in = new Scanner(System.in);
Scanner inFile = new Scanner(new File("hurcData2.txt"));
System.out.println(headerData);
/**---Use for-each (line:token)
* Parse for year - > year array
* parse for name - > name array
* parse for knots - > tempKnots
* knotsToMph = tempKnots * 1.15078
* hurricaneWindSpeed[counter] = knotsToMph
* enter if-else to calculate category (hurricaneCategory [] = 1,2,3,4, or 5):
* 74-95 cat1
* 96-110 cat2
* 111 - 129 cat3
* 130-156 cat4
* 157 or higher cat 5
*
*
*/
while(inFile.hasNextLine()){
token[counter] = inFile.nextLine();
String tempToken = token[counter];
hurricaneYear[counter] = tempToken.substring(0, 3);
hurricaneMonth[counter] = tempToken.substring(6, 8);
hurricanePressure[counter] = Double.parseDouble(tempToken.substring(10, 12));
hurricaneWindSpeed[counter] = Double.parseDouble(tempToken.substring(14, 16));
hurricaneName[counter] = tempToken.substring(17);
counter++;
}
System.out.print("Lines: " + counter);
}
}
You can split the string into arrays with regex:
String s = "1980 Aug 945 100 Allen";
Pattern p = Pattern.compile("\\s+");
System.out.println(Arrays.toString(p.split(s)));
or using the String.split method:
System.out.println(Arrays.toString(s.split("\\s+")));
output:
[1980, Aug, 945, 100, Allen]
[1980, Aug, 945, 100, Allen]
The title of the question lists index out of bounds exception, but it does not say if it is StringIndexOutOfBoundsException or ArrayIndexOutOfBoundsException.
You read the lines into an array that is defined to hold 1000 elements, but then put the parsed pieces of the string into arrays that are only defined to hold 64 elements.
It could be that your parsing logic is OK but the array's are getting over filled.
You could probably do something like this:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class test {
public void converter(String[] stringArray) {
int counter = 0;
String [] token = new String[1000];
String [] tokenElements = new String[128];
String [] hurricaneYear = new String[64];
String [] hurricaneName = new String[64];
String [] hurricaneMonth = new String[64];
int [] hurricaneCategory = new int[64];
double [] hurricanePressure = new double[64];
double tempKnots;
double knotsToMph;
double [] hurricaneWindSpeed = new double[64];
double categoryAverage;
double pressureAverage;
double speedAverage;
String headerData = " Hurricanes 1980 - 2006\n\n Year Hurricane Category Pressure(MB) Wind Speed (MPH)\n========================================================================";
Scanner in = new Scanner(System.in);
Scanner inFile = null;
try {
inFile = new Scanner(new File("hurcData2.txt"));
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
while(inFile.hasNextLine()){
String line = inFile.nextLine();
String[] arrayOfString = line.split(" ");
}
System.out.print("Lines: " + counter);
}
}
The issue with incompatible types is because you have to convert the Scanner object to a String. I did that in the while loop, so now while the scanner has a next line its going to turn that line into a string and split it on the spaces. You will have an array for all the values. Now you can perform your logic based on the position in the array.

How to make Code more efficient/clean - USACO Training First Task

I'm having trouble with the first problem on the USACO Training Page.
The task is asking for two strings from a text.in file, converting the strings into a number that is the product of the letters (where a=1, b=2, z=26), then seeing if the remainders of the numbers/47 are equal to each other (if they are, print "GO", if not, print "STAY").
It works great on my computer, but when I send it in, it displays
Run 1: Execution error: Your program exited with exit status `1'.
------ Data for Run 1 [length=14 bytes] ------
COMETQ
HVNGAT
----------------------------
Your program printed data to stderr. Here is the data:
-------------------
Exception_in_thread_"main"_java.io.FileNotFoundException:_test.in_(No_such_file_or_directory)
at_java.io.FileInputStream.open(Native_Method)
at_java.io.FileInputStream.<init>(FileInputStream.java:106)
at_java.io.FileInputStream.<init>(FileInputStream.java:66)
at_java.io.FileReader.<init>(FileReader.java:41)
at_ride.main(Unknown_Source)
I tried looking at this http://cerberus.delos.com:790/usacoprobfix?a=VjAAvKvQucH , but I couldn't really understand terms such as "stack usage" or "out-of-bounds".
Is the reason why it is not accepting my code because it is too slow? I would appreciate any help figuring out this problem.
/*
ID: Anon
LANG: JAVA
TASK: ride
*/
import java.io.*;
import java.util.*;
class ride
{
public static void main (String [] args) throws IOException
{
//input
BufferedReader br = new BufferedReader(new FileReader("test.in"));
//output
PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("test.out")));
String nameComet = br.readLine();
String nameGroup = br.readLine();
int productComet = 1;
int productGroup = 1;
//loop through each letter in word
for(int i=0; i<nameComet.length(); i++)
{
//sets letter to char letter
char letter = nameComet.charAt(i);
//set number of letter to correspondnum
int numComet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ".indexOf(letter) + 1;
productComet *= numComet;
}
for(int i=0; i<nameGroup.length(); i++)
{
//sets letter to char letter
char letter = nameGroup.charAt(i);
//set number of letter to correspondnum
int numGroup = "ABCDEFGHIJKLMNOPQRSTUVWXYZ".indexOf(letter) + 1;
productGroup *= numGroup;
}
int modComet = productComet % 47;
int modGroup = productGroup % 47;
if (modComet == modGroup)
{
out.println("GO");
}
else
{
out.println("STAY");
}
//close everything
out.close();
System.exit(0);
}
}
Your error is on these lines:
BufferedReader br = new BufferedReader(new FileReader("test.in"));
PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("test.out")));
Your code is attempting to read from a file ("test.in") that doesn't exist on the usaco servers. When you submit your code to the website, you need to read from files that have the same name as that of the problem (e.g. "ride.in" and "ride.out").
Hope that helps!

Categories