简体   繁体   中英

How to read a .txt file for each int on a line & storing to array?

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

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM