0
public class assignment2
{
    public static void main(String[] args) throws IOException 
    {
        // TODO Auto-generated method stub
        FileInputStream fstream = new FileInputStream("assignment2.txt");
        BufferedReader br = new BufferedReader(new InputStreamReader(fstream));

        String strLine;

        //Read File Line By Line
        while ((strLine = br.readLine()) != null) {
            // Print the content on the console
            System.out.println (strLine);
            String[] numbers = strLine.split(" ");
            System.out.print(numbers[1]);
        }
        //Close the input stream
        br.close();
    }
}

I expect that the code will print the String[] numbers as 1 0 10

I get this result 00371010

Please note that the input file is formatted as such:

1 0 10

2 0 9

3 3 5

4 7 4

5 10 6

6 10 7

JpersaudCodezit
  • 143
  • 2
  • 13
  • you are printing `numbers[1]` from each line that is second number from each line. So what do you expect to get printed. Try this `System.out.print(number[0] + " " + numbers[1] + " " + numbers[2]);` it will work as you need – jack jay Dec 05 '17 at 15:09

2 Answers2

3

Just replace your line:

System.out.print(numbers[1]);

With:

for (int i = 0; i < numbers.length; i++)
    System.out.print(numbers[i] + " ");

System.out.println();

Let me know how it works.

whatamidoingwithmylife
  • 1,119
  • 1
  • 16
  • 35
1

You need to modify the code by adding another loop like this:

public static void main(String[] args) throws IOException {
    // TODO Auto-generated method stub
    FileInputStream fstream = new FileInputStream("assignment2.txt");
    BufferedReader br = new BufferedReader(new InputStreamReader(fstream));
    String strLine;

    //Read File Line By Line
    while ((strLine = br.readLine()) != null){
        // Print the content on the console
        System.out.println (strLine);
        String[] numbers = strLine.split(" ");
        for (String num : numbers){
            System.out.print(num + " ");
        }
        System.out.println("\n");
    }
    //Close the input stream
    br.close();
}

Because, numbers[1] will only print the value at index 1.

  • It prints an extra blank space at the end of each line. –  Dec 05 '17 at 15:22
  • Also i want to store these values in numbers[ ] & use it throughout the code, i tried to create the array outside of the while loop but when I try to access the data after loop it is not there, how do i do this? – JpersaudCodezit Dec 05 '17 at 19:30