这个while循环只是永远循环。我查找了解决方案并尝试添加消耗输入的内容,但这没有帮助。 printf" readDONEZO"没有打印。
这是我的代码
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;
}
}
答案 0 :(得分:-1)
您的代码中的问题是您永远不会关闭扫描程序,因为stdin随时可以接收新输入。
出于这个原因,stdin.hasNextLine()
while条件始终为true,它使while循环成为无限循环。如果您将扫描仪的输入(System.in
)替换为工作站中文件的路径,则该示例将正常工作,因为该文件具有最后一行。