在過去的幾天里,我一直在為我的班級做一個專案,并且反復遇到同樣的錯誤。我在 Visual Studio 代碼中作業,該專案的目標是使用方法和掃描 .txt 檔案制作生活游戲。每當我嘗試編譯代碼時,都會出現同樣的錯誤訊息。這是有問題的代碼:
import java.io.*;
import java.util.Scanner;
public class GameOfLife3 {
public static final char ON = 'X';
public static final char OFF = '*';
public static int fileRow, fileColumn;
public static int array[][];
public static char board[][];
public static char nextBoard[][];
public static int nextArray[][];
public static Scanner scan = new Scanner(System.in);
public static int[][] readGrid(String fileName) throws IOException{
File file = new File(fileName);
Scanner scan2 = new Scanner(file);
fileRow = scan2.nextInt();
fileColumn = scan2.nextInt();
array = new int[fileRow][fileColumn];
for(int i = 0; i < fileRow; i ){
for(int j = 0; j < fileColumn; j ){
array[i][j] = scan2.nextInt();
}
}
return array;
(there is more code in between here but thats not the part I am having trouble on)
public static void main(String[] args) throws IOException{
String fileName;
System.out.print("Please enter the name of the file you want to use (name.txt): ");
fileName = scan.nextLine();
array = readGrid(fileName);
}
}
我知道它很亂,但我稍后會修復它。
這也是我要使用的 .txt 檔案。(名稱是 Blinker.txt)
5 5
00000
00000
01110
00000
00000
我嘗試做的一些事情是使用 .hasNextInt() 函式來檢查 .txt 的時間,但它不起作用。任何幫助將不勝感激。
uj5u.com熱心網友回復:
這NoSuchElementException不是編譯錯誤 - 它是在運行時引發的例外。(Java 編譯器無法知道您的輸入檔案包含多少值,因此無法報告此類錯誤。)
對我來說,它被拋出的原因很清楚:您從檔案中讀取兩個整數 5 和 5,然后嘗試從檔案中讀取另外 25 個整數值 - 但您的檔案(在這兩個值之后)僅包含 5 個值:0 , 0, 1110, 0 和 0。
nextInt()不是讀取資料的正確方法。而不是你應該使用next()(讀取包含 0 和 1 的字串)然后拆分它們:
for (int i = 0; i < fileRow; i ) {
String s = scan2.next();
for (int j = 0; j < fileColumn; j ) {
array[i][j] = Integer.parseInt(s.substring(j, j 1));
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/524314.html
標籤:爪哇文件方法
