gpt4 book ai didi

java - 为什么这不会打印任何整数?

转载 作者:行者123 更新时间:2023-11-30 08:07:14 25 4
gpt4 key购买 nike

try {

Scanner sc = new Scanner(new File("testing.txt"));

while (sc.hasNextInt()){
int i = sc.nextInt();
//timing.add(i);
System.out.println(i);
}

sc.close();

}catch (FileNotFoundException e) {
e.printStackTrace();
}

文本文件中确实有 int 和 strings。我可以让它打印文本文件中的单词,但不能打印数字。

文本文件包括以下内容:

Michael 3000
7000 Bilbo
I like the number 2000 do you?
No, I like 9000

最佳答案

您的第一个值(“Michael”)不是整数,因此它永远不会进入循环体。

也许您想将代码更改为循环直到到达文件末尾,读取并打印整数,但使用(不打印)非整数值。所以像这样:

import java.util.*;
import java.io.*;

public class Test {
public static void main(String[] args) throws Exception {
Scanner sc = new Scanner(new File("test.txt"));

while (sc.hasNext()) {
if (sc.hasNextInt()) {
System.out.println(sc.nextInt());
} else {
// Just consume the next token
sc.next();
}
}
sc.close();
}
}

关于java - 为什么这不会打印任何整数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33830718/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com