assigning strings and int from a file and then manipulating the data
Hi, I am very, very new to Java and I have a homework assignment, which (obviously) I have left to the very last minute.
I have read from a file and displayed the information, and seemed to have spilt the information up into strings. Now I need to use those strings: change two of them into int and then add up the int seperately...which I have no idea how to do. Tried a number of things, such as a Demlimiter but didn't work - possibly as I did not use it correctly!
This is the information I am reading from the file
"Leeds United : Liverpool : 1 : 2
Chelsea : Manchester City : 1 : 1
Aston Villa : Middlesbrough : 3 : 1
Tottenham Hotspur : Stoke City : 0 : 0"
Can anyone help please??!!
Here is my code that I have got so far
"
Code:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class Generator {
/**
* @param args
* @throws FileNotFoundException when the file cannot be loaded
*/
public static void main(String[] args) throws FileNotFoundException {
Scanner s = new Scanner(new File("Demo.txt")); // create a scanner which scans from a file
String line; // stores the each line of text read from the file
while ( s.hasNext() ) {
line = s.nextLine(); // read the next line of text from the file
String [] splitupText = "Demo.text".split(":"); // split the text into multiple elements
for ( int i = 0; i < splitupText.length; i++ ) { // loop over each element
String nextBit = splitupText[i]; // get the next element (indexed by i)
nextBit = nextBit.trim(); // use the trim method to remove leading and trailing spaces
try { // "try" is a special statement which allows us to deal with "exceptions"
int num = Integer.parseInt(line); // attempt to convert the String into an Integer type value
}
catch (NumberFormatException e) {
// The number did not parse for some reason
System.out.println("Invalid number entered");
}
System.out.println(line); // output the line of text to the console
}
}
}
}
"
The try method doesn't parse properly and displays the error message after each string.
Like
"Invalid number entered
Leeds United : Liverpool : 1 : 2
Invalid number entered
Chelsea : Manchester City : 1 : 1
Invalid number entered"