2016-09-18 63 views
0

此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; 
} 
} 
+0

只是爲了記錄:調用變量stdin有點混亂。或者您是否認爲您真的不希望將這種方法用於來自不同來源的掃描儀? – GhostCat

+0

你正在閱讀的是什麼來源?它是文件,還是'System.in'? – Pshemo

+0

我試過你的代碼,它工作正常(我評論了與細胞有關的兩條線)。是否有可能看到你如何稱呼該方法? – acornagl

回答

-1

在你的代碼的問題是,你永遠不會關閉掃描儀,因爲標準輸入時刻準備着接收新的輸入。

由於這個原因,stdin.hasNextLine() while條件總是爲true,並且它使得while循環成爲一個無限循環。如果將掃描儀的輸入(System.in)替換爲工作站中文件的路徑,則該示例將正常工作,因爲該文件具有最後一行。