1

Essentially I have a file of lines of integers. Each line has 9 digits. And I want to read the file. And then input each line into its an array. I want the array to be the same one each time. As I am going to do some processing to the array created from the first line. And then process the same array using a different line.

My input file is as follows:

8 5 3 8 0 0 4 4 0 8 5 3 8 0 0 4 2 2 

And the current code that I am using is:

 BufferedReader br = new BufferedReader(new FileReader("c:/lol.txt")); Scanner sc = new Scanner(new File("c:/lol.txt")); String line; while (sc.hasNextLine()){ line = sc.nextLine(); int k = Integer.parseInt(line); 

Now clearly I should be doing something more, I am just not really sure how to go about it.

Any help is greatly appreciated.

3
  • 1
    Have you run your code? It should throw an exception here: int k = Integer.parseInt(line); because a whole line can't be converted to one number. (There are many digits and spaces). Also you create a BufferedReader and never use it. Is your question how to finish your program? Commented Nov 12, 2012 at 20:52
  • 2
    Adding to jlordo's comment, you'll want to grab the integer values based on a space delimiter . line.split(" "); Commented Nov 12, 2012 at 20:57
  • What do you mean with "As I am going to do some processing to the array created from the first line. And then process the same array using a different line." exactly? Commented Nov 12, 2012 at 21:18

1 Answer 1

1

Try:

import java.util.Scanner; import java.io.File; public class Test { public static void main(String[] args) throws Exception { Scanner sc = new Scanner(new File("c:/lol.txt")); while (sc.hasNext()) { String line = sc.nextLine(); // get String array from line String[] strarr = line.split(" "); // attention: split expect regular expression, not just delimiter! // initialize array int[] intarr = new int[strarr.length]; // convert each element to integer for (int i = 0; i < strarr.length; i++) { intarr[i] = Integer.valueOf(strarr[i]); // <= update array from new line } } } } 

Of course, you should handle exception instead to pass it.

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

4 Comments

Basically did the whole assignment for him aside from adding them to an integer array. Add some comments in there for he understands what is happening :)
I think I completely misunderstood the question... I updated my answer.
I'd move the int array assignment and change it to int[] intarr = new int[strarr.length]; also, to work with different lengths.
It's was my second version, but "As I am going to do some processing to the array created from the first line.". Comment this now on question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.