java - 将第一个、第二个和第三个 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:[]
解决方案
你从来没有打电话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());
}
推荐阅读
- c - 中断按钮和 LED 无法正常工作
- python - 如何在 python 中获取随机 youtube 视频,不和谐
- javascript - React-Native, Redux / reducer 收到的先前状态具有意外类型的“函数”
- javascript - 使用递归打印对象属性
- haskell - 使用已知变量字段解析 JSON
- java - 是否可以将变量用作 XML 中的值?(JAVA)
- regex - 正则表达式计数不匹配(字符串中的偶数“a”和“b”)
- bash - 如何从下往上将日志文件截断为最大行数?
- python - 我的验证准确度为零
- html - 如何在 HTML 中集成 SSH