作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在运行一些代码来从文件中读取数据,然后将每一行拆分为一个数组以便于计算。
但是,我遇到了一个问题,尽管我知道文本文件中有更多数据,但我的 while 循环没有继续。
任何有关该问题的帮助将不胜感激!
public void test() throws IOException {
FileReader fr = null;
Scanner sc = null;
String file_name = "data.txt";
try {
fr = new FileReader(file_name);
sc = new Scanner(fr);
while(sc.hasNextLine()){
int year = 0;
int month = 0;
double sales_total = 0;
String lines[] = sc.nextLine().split(" ");
for (int i = 0; i < lines.length; i++){
int value = Integer.valueOf(lines[i]);
if (value > 2000) {
year = value;
}
else if (i == 1){
month = value;
}
else {
sales_total += value;
}
System.out.println(sales_total);
}
System.out.println(year + " - " + month + " - "+sales_total);
}
}
catch(IOException e) {
System.out.println(e);
}
finally {
if (fr != null) { fr.close();}
if (sc != null) { sc.close();}
}
}
数据.txt
2016 02 5 18 12
2016 12 14 10 3 5 6 8 20 7 10
2016 09 17 3 16 18 19 10 6 10
2016 10 5 3 12 4 12 15
2016 11 18 19 16 2
2017 01 5 5 4 11
2017 02 41 3
2017 06 3 6 18
2017 07 15 18 15 12 9 15
2017 11 9 8 9 4 20 20 19 3
2018 01 19 19 3 10 20 20 18 14 3
2017 12 8 13 18 6
2018 11 10 2 11 8 17 8 6 18 15 1
最佳答案
sc.nextLine 和 sc.hasNextLine 在设计上是阻塞调用,因此它将保持阻塞状态,直到有新输入进入。请参阅 Scanne.hasline() documentation
是否是代码中的某些行缺少 CR LF 分隔符?我拿了你的样本,用 Notepad++ 打开它并查看了空白(在 View ->显示符号下)。并看到以下内容:
...
2017 11 9 8 9 4 20 20 19 3 CR LF
2018 01 19 19 3 10 20 20 18 14 3 CR LF
2017 12 8 13 18 6 CR LF
2018 11 10 2 11 8 17 8 6 18 15 1
关于Java Scanner - While 循环不继续,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55484680/
我是一名优秀的程序员,十分优秀!