1

I need help with an assignment that I have. My assignment asks me to calculate test scores from a text file.

For example, my text file ("input.txt") shows this:

Lois Lane,         100, 98, 95, 90, 93, 88, 92
Marie Calendar,    85, 82, 88, 78, 85, 86, 90
Bob Marley,        70, 75, 72, 78, 80, 82, 76
Tom Brady,         82, 90, 88, 95, 92, 86, 87
Clark Kent,        99, 98, 100, 96, 100, 97, 95
Sandra Dee,        95, 93, 90, 100, 98, 89, 92

I would like to be able to calculate just the scores (by column).

I successfully read the file. However, I am having a hard time figuring out why Integer.ParseInt throws a "NumberFormatException".

This is the code I have so far.

public class testAvg {

public static int main(String[] args) throws IOException {

    String token1 = " ";

    Scanner inFile = new Scanner(new File("input.txt")).useDelimiter(",\\s*[a-z][A-Z]");

    List<String> inputs = new ArrayList<String>();

    while (inFile.hasNext()) {
        token1 = inFile.next();
        inputs.add(token1);
    }
    inFile.close();


    String[] inputsArray = inputs.toArray(new String[1]);

    int parsedArray = 0;

    for (int i = 0; i < inputsArray.length; i++) {
        parsedArray = Integer.parseInt(inputsArray[i]);   // This line throws the exception
    }
    return parsedArray;

} 
}

Any help would be greatly appreciated!

4
  • 2
    Post the content of input.txt. Commented Nov 10, 2015 at 4:25
  • May we see the text file please? Showing the code won't be enough Commented Nov 10, 2015 at 4:25
  • The problem is the names are part of the input. Your results of inFile.next() are "Lois Lane" (a string with no digits, which isn't an integer, hence the error) followed by "100", "98", "95", "90", "93", "88", "92", "Marie Calendar", etc. Commented Nov 10, 2015 at 4:29
  • @billjamesdev Look at the useDelimiter() call. It actually doesn't work at all, so the entire text is returned by next(). It works if the regex is changed to "[a-zA-Z\\s]*,\\s*". Commented Nov 10, 2015 at 4:44

3 Answers 3

1

Since this is a homework assignment, I'm not going to give you the full answer, but you should forget about Scanner.

Use a BufferedReader, and call the readLine() method. Split the line using split("\\s*,\\s*"). The returned array will have the name in [0] and the numbers in [1] ... [7]. Call parseInt() on those.

Sign up to request clarification or add additional context in comments.

9 Comments

Thanks! I'll try that. :)
But, for the error in your code, the regex should be "[a-zA-Z\\s]*,\\s*". A comma, any trailing whitespace, and any leading whitespace and/or letters.
Actually, scanner.nextLine() can also be used. He will still have to separate out the text part from the numbers part. BufferedReader would be faster than Scanner though :)
@VinodMadyalkar Yeah, Scanner is a beast, performance-wise. For simple line reading, BufferedReader is the way to go.
@Andreas: I went with your BufferedReader suggestion and solved it. :)
|
0

inputsArray[0] will contain

Lois Lane, 100, 98, 95, 90, 93, 88, 92

Marie Calendar, 85,82, 88, 78, 85, 86, 90

Bob Marley, 70, 75, 72, 78, 80, 82, 76

Thats why its not able to parse that string.

Integer.parseInt() takes only numbers in String format

1 Comment

It actually contains the entire text, not just the first line.
0

You see your code

 for (int i = 0; i < inputsArray.length; i++) {
        parsedArray = Integer.parseInt(inputsArray[i]);   // This line throws the exception
    }

will throw an error since there are String values which cannot be converted to int.

Use this code

import java.awt.List;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Scanner;

    public class testAvg {

        public static void main(String[] args) throws IOException {
            int[] receivedArray = getArray();
            System.out.println("The received array is");
            for (int i : receivedArray) {
                System.out.println(i);
            }
        }

        public static int[] getArray() throws FileNotFoundException {
            String line;

            Scanner inFile = new Scanner(new File("input.txt"));
    //        inFile.useDelimiter(",");

            ArrayList<Integer> inputs = new ArrayList<Integer>();

            while (inFile.hasNextLine()) {
                line = inFile.nextLine();//use nextLine to get the complete line
                String nums = line.substring(1 + line.indexOf(",")).replace(" ", "");//removing the name from each line
                String[] num = nums.split(",");//split the nums
                for (String number : num) {
                    inputs.add(Integer.parseInt(number));//Directly parsing the int values
                }
            }
            inFile.close();
            int[] passedArray = new int[inputs.size()];
            for (int i = 0; i < inputs.size(); i++) {
                passedArray[i] = inputs.get(i);//converting to int
            }
            return passedArray;
        }
    }

6 Comments

Why convert inputs to inputsArray? Just use inputs.get(i) in the loop. And why new Integer[1], and not size 0 or inputs.size()? --- Using catch exception to ignore parse errors is ... discouraged.
@Andreas I didn't change the whole source code. Just made a quick review and change the error lines.
Thank you and @Andreas for the suggestions! I truly appreciate it. :)
@Sugarcoder you can now use the modified code if you want.
@shivam7357: the last column of numbers was not parsed for some reason. It was left out of the result. :/
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.