.hasNextLine()永久循环
问题描述:
此while循环只是永远循环。我查找了解决方案,并试图添加一些消耗输入的内容,但这并没有帮助。 printf“readDONEZO”未打印。.hasNextLine()永久循环
这里是我的代码
public void read(Scanner stdin) {
int sRow = 0;
while (stdin.hasNextLine()) {
String theLine = stdin.nextLine();
String[] split = theLine.split(",");
int size = split.length; //how many values in array = 3
for(int i = 0; i < size ; i++){
String value = split[i];
int sColumn = i;
setCellValue(sRow, sColumn, value);
System.out.printf("%s", getCellValue(sRow,sColumn));
if (i+1 != size) {
System.out.printf(",");
}
}
sRow += 1;
System.out.printf("\n");
}
System.out.printf("readDONEZO\n");
}
主要
import java.io.*;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
int rows = 100;
int columns = 26;
StringSpreadsheet a = new StringSpreadsheet(rows, columns);
Scanner stdin = new Scanner(System.in);
a.read(stdin);
System.out.printf("out of read\n");
a.write();
}
}
类
import java.util.Scanner;
public class StringSpreadsheet {
private int rows;
private int columns;
private String[][] cells;
private int allRows;
private int allColumns;
public StringSpreadsheet(int rows, int columns) {
allColumns = 0;
allRows = 0;
this.rows = rows;
this.columns = columns;
cells = new String[this.rows][this.columns];
}
public void read(Scanner stdin) {
while (stdin.hasNextLine()) {
String theLine = stdin.nextLine();
String[] split = theLine.split(",");
allColumns = split.length; //how many values in array = 3
for(int i = 0; i < allColumns ; i++){
String value = split[i];
int sColumn = i;
setCellValue(allRows, sColumn, value);
System.out.printf("%s", getCellValue(allRows,sColumn));
if (i+1 != allColumns) {
System.out.printf(",");
}
}
allRows += 1;
System.out.printf("\n");
}
System.out.printf("readDONEZO\n");
}
public void write() {
for (int i = 0 ; i < allRows ; i++){
for(int j = 0 ; j < allColumns ; j++){
String value = getCellValue(i, j);
if()
System.out.printf("%s,", value);
}
}
}
public String getCellValue(int gRow, int gColumn) {
return cells[gRow][gColumn];
}
public void setCellValue(int sRow, int sColumn, String value) {
cells[sRow][sColumn] = value;
}
}
答
在你的代码的问题是,你永远不会关闭扫描仪,因为标准输入时刻准备着接收新的输入。
由于这个原因,stdin.hasNextLine()
while条件总是为true,并且它使得while循环成为一个无限循环。如果将扫描仪的输入(System.in
)替换为工作站中文件的路径,则该示例将正常工作,因为该文件具有最后一行。
只是为了记录:调用变量stdin有点混乱。或者您是否认为您真的不希望将这种方法用于来自不同来源的扫描仪? – GhostCat
你正在阅读的是什么来源?它是文件,还是'System.in'? – Pshemo
我试过你的代码,它工作正常(我评论了与细胞有关的两条线)。是否有可能看到你如何称呼该方法? – acornagl