如何将一行存储在数组中?

huangapple go评论70阅读模式
英文:

How to store a line in an Array?

问题

public class Main {
    public static void main (String[] Args) throws IOException {
        /*Getting the file and going through each line*/
        File planeFile = new File("plane.txt");
        Scanner scanFile = new Scanner(planeFile);

        /*Array to store the flights in*/
        String[] flights = new String[50];

        int index = 0; // Index to keep track of array position
        
        while(scanFile.hasNext()) {
            flights[index] = scanFile.nextLine();
            index++; // Increment the index
        }
        
        scanFile.close(); // Close the scanner
        
        // Displaying the array contents
        for (String flight : flights) {
            if (flight != null) {
                System.out.println(flight);
            }
        }
    }
}
英文:

I have been trying to store a ling in a text file in array but I have no been able to do anything about it and I cannot use ArrayList which means it needs to be done manually. This is my code at the moment. By the way, the first line in the text file(the header) should not be included in the array.

public class Main {
    public static void main (String[] Args) throws IOException {
        /*Getting the file and going through each line*/
        File planeFile = new File("plane.txt");
        Scanner scanFile = new Scanner(planeFile);

        /*Array to store the flights in*/
        String[] flights = new String[50];

        while(scanFile.hasNext()) {
            for(int i = 0; i < flights.length; i++) {
                flights[i] = scanFile.nextLine();
            }
        Arrays.toString(flights);
        }

    }
}

This is the output for my code:

Exception in thread "main" java.util.NoSuchElementException: No line found
        at java.base/java.util.Scanner.nextLine(Scanner.java:1651)
        at Main.main(Main.java:20)

But I need it to store each line of my text file in an array. This is the file:

ID, Destination, Day, Meal, Rows, NumPerRow
9010, Florida, 3, no, 22, 4
9002, Florida, 1, no, 22, 4
9005, Florida, 1, yes, 32, 5
9013, Florida, 3, yes, 32, 5
9008, Florida, 2, yes, 32, 5
9024, Florida, 6, yes, 32, 5
9016, Florida, 4, yes, 32, 5
9021, Florida, 5, yes, 32, 5
9018, Florida, 5, no, 22, 4
9029, Paris, 7, yes, 32, 5
9026, Bahamas, 7, no, 22, 4
9007, Boston, 2, no, 24, 4
9015, Boston, 4, no, 24, 4
9023, Boston, 6, no, 24, 4
9009, NYC, 2, yes, 32, 5
9012, NYC, 3, yes, 32, 5
9004, NYC, 1, yes, 32, 5
9025, NYC, 6, yes, 32, 5
9017, NYC, 4, yes, 32, 5
9020, NYC, 5, yes, 32, 5
9011, Chicago, 3, no, 24, 4
9019, Chicago, 5, no, 24, 4
9003, Chicago, 1, no, 24, 4
9014, DC, 4, no, 22, 4
9006, DC, 2, no, 22, 4
9022, DC, 6, no, 22, 4
9027, Jamaica, 7, no, 24, 4
9028, London, 7, yes, 32, 5

答案1

得分: 1

Your code will loop for the length of the array, which is hardcoded in this snippet as: 50 slots.

Your file contains fewer than 50 flights, thus, this error occurs.

I'd give advice on how to do such things, but your question goes out of its way to try to impress on us how this boneheaded model of storing this data in a string array is somehow required, so I guess it's.. required.

You said it's required, and your code says that there are 50 flights. Find a way to know beforehand how many flights there are, or arrange for 50 flights to be in the file, or expand on the problem domain to explain what should be done when the file contains fewer than 50 flights (or for that matter, what should happen if there are more than 50 flights).

NB: If your answer is: The array should be exactly as large as there are flight-lines in my text file, then you want ArrayList, not String[]. Note that an ArrayList can rather trivially give you a String[] if you need that someplace else. If this too is not okay, then, well, the java libs are open source. Have a look at how ArrayList works, because you'll be writing a clone of it.

英文:

Your code will loop for the length of the array, which is hardcoded in this snippet as: 50 slots.

Your file contains fewer than 50 flights, thus, this error occurs.

I'd give advice on how to do such things, but your question goes out of its way to try to impress on us how this boneheaded model of storing this data in a string array is somehow required, so I guess it's.. required.

You said it's required, and your code says that there are 50 flights. Find a way to know beforehand how many flights there are, or arrange for 50 flights to be in the file, or expand on the problem domain to explain what should be done when the file contains fewer than 50 flights (or for that matter, what should happen if there are more than 50 flights).

NB: If your answer is: The array should be exactly as large as there are flight-lines in my text file, then you want ArrayList, not String[]. Note that an ArrayList<String> can rather trivially give you a String[] if you need that someplace else. If this too is not okay, then, well, the java libs are open source. Have a look at how ArrayList works, because you'll be writing a clone of it.

答案2

得分: 1

你是否意识到你有两个嵌套循环:
内部的 for 循环将迭代 50 次(或者在你的注释更改后为 30 次),并读取整个文件。
你只调用了一次 hasNext()。你必须在每次调用 scanner.nextLine() 之前调用 scanner.hasNext(),以确保有一行或多行可供读取。

你之所以出错是因为你的文件只有 29 行。
如果你知道文件中的最大行数,最好依赖于 scanner.hasNext() 的逻辑:

public static void main(String[] Args) throws IOException {
    /*获取文件并逐行处理*/
    File planeFile = new File("plane.txt");
    Scanner scanFile = new Scanner(planeFile);

    /*存储航班的数组*/
    String[] flights = new String[50];
    int i = 0;
    scanFile.nextLine(); // 跳过标题行
    while (scanFile.hasNext()) {
        flights[i] = scanFile.nextLine();
    }
}
英文:

Are you aware you have 2 nested loops:
The inner for-loop will iterate 50 times (or 30 after your commented change) and read the whole file.
You call hasNext() only once. You must change your code so before each call to scanner.nextLine() you have called scanner.hasNext()to asure there is one more line.

You have the error because your file has only 29 lines.
If you know the maximum number of lines in the file it's better to rely on the scanner.hasNext() logic:

public static void main (String[] Args) throws IOException {
    /*Getting the file and going through each line*/
    File planeFile = new File(&quot;plane.txt&quot;);
    Scanner scanFile = new Scanner(planeFile);

    /*Array to store the flights in*/
    String[] flights = new String[50];
    int i=0;
    scanner.nextLine(): // skip header line
    while(scanner.hasNext())
    {
        flights[i] = scanFile.nextLine();
    }
}

huangapple
  • 本文由 发表于 2020年9月14日 04:46:17
  • 转载请务必保留本文链接:https://go.coder-hub.com/63875415.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定