首页 > 解决方案 > 将第一个、第二个和第三个 int 扫描器值分配给 3 个不同的队列

问题描述

我在将使用扫描仪从 dat 文件读取的整数分配给不同的队列时遇到了一些麻烦。经过一番搜索,我设法弄清楚如何读取文件中的 int 值并将它们分配给单个队列,但是我不知道如何将每行的第一个值分配给一个特定的队列,比如说 Q1,同一行的第二个值到 Q2,第三个值到 Q3。当我尝试这样做时,当我尝试打印它们时,我会得到来自完全不同行的奇怪值。

这是我到目前为止所拥有的:

public static void main(String[] args) throws FileNotFoundException 
    {
        System.out.print("Enter the file name with extension : ");

        Scanner input = new Scanner(System.in);

        File file = new File(input.nextLine());

        input = new Scanner(file);

        int numPS = input.nextInt();
        int numSS = input.nextInt();

        System.out.println(numPS);
        System.out.println(numSS);

        Queue<Integer> Mins = new LinkedList<>();
        Queue<Integer> MinsPS = new LinkedList<>();
        Queue<Integer> MinsSS = new LinkedList<>();

        while (input.hasNextInt()) 
        {
            if(input.hasNext()) 
            {
            int numofmins = input.nextInt();
            Mins.add(numofmins);
            }
        }
        System.out.println("Elements of Mins:"+Mins);
        System.out.println("Elements of MinsPS:"+MinsPS);
        System.out.println("Elements of MinsSS:"+MinsSS);

         input.close();
    }

.dat 文件的内容如下:

3 2 
1 2 3 
3 3 5 
3 2 2 
4 3 2 
5 2 4 
0 0 0 

使用当前代码,这是输出。第一个队列显示 .dat 文件中的所有值,但我想要的是分别在 3 个队列中的每一个中的每行的第一个第二个和第三个值。

3
2
Elements of Mins:[1, 2, 3, 3, 3, 5, 3, 2, 2, 4, 3, 2, 5, 2, 4, 0, 0, 0]
Elements of MinsPS:[]
Elements of MinsSS:[]

标签: java

解决方案


你从来没有打电话MinsPS.add()MinsSS.add()当然他们里面没有任何东西。

scanner.nextInt()您可以在同一个循环中简单地调用3 次。

例如:

Queue<Integer> queue1, queue2, queue3 ...
Scanner scanner = ...
while (scanner.hasNext()) {
    queue1.add(scanner.nextInt());
    if (scanenr.hasNext()) queue2.add(scanner.nextInt());
    if (scanenr.hasNext()) queue3.add(scanner.nextInt());
}

推荐阅读