Java 从文件读取时没有此类元素异常

Java 从文件读取时没有此类元素异常,java,Java,我知道这是一个经常被问到的问题,但是,我不知道为什么即使在做了研究之后也会出现错误 import java.io.*; import java.util.*; public class readfile { private Scanner x; public void openFile(){ try{ x = new Scanner(new File("input.txt")); } catch(Exc

我知道这是一个经常被问到的问题,但是,我不知道为什么即使在做了研究之后也会出现错误

import java.io.*;
import java.util.*;

public class readfile {

    private Scanner x;

    public void openFile(){
        try{
            x = new Scanner(new File("input.txt"));
        }
        catch(Exception e){
            System.out.println("Oh noes, the file has not been founddd!");
        }
    }

    public void readFile(){
        int n = 0;
        n = Integer.parseInt(x.next()); //n is the integer on the first line that creates boundaries n x n in an array.

        System.out.println("Your array is size ["+ n + "] by [" + n +"]");

        //Create n by n array.
        int[][] array = new int[n][n];

        //While there is an element, assign array[i][j] = the next element.
        while(x.hasNext()){
             for(int i = 0; i < n; i++){
                 for(int j = 0; j < n; j++){
                     array[i][j] = Integer.parseInt(x.next());
                     System.out.printf("%d", array[i][j]);
                 }
                System.out.println();
             }
        }
    }

    public void closeFile(){
        x.close();
    }
}

看起来您的代码将整行读取为int,这些数字中的每一个都是:

0110011 1000000 1001000 0010001 0000001 1000001
是指构成每行的7位数字吗

如果是这种情况,则需要将每个值拆分为其相应子数组的组成部分

在这种情况下,请使用此代码段:

   while(x.hasNext()){
         for(int i = 0; i < n; i++){
             String line = x.next();
             for(int j = 0; j < n; j++){
                 array[i][j] = line.charAt(j) - '0';
                 System.out.printf("%d", array[i][j]);
             }
            System.out.println();
         }
    }
while(x.hasNext()){
对于(int i=0;i
Output:java.util.Scanner.throwFor(未知源)at java.util.Scanner.next(未知源)at readfile.readfile(readfile.java:32)at vertices.main(vertices.java:8)的线程“main”java.util.NoSuchElementException中的数组大小为[7]乘以[7]0110010110011000000 1001000 00100001异常[i] [j]=Integer.parseInt(x.next())我不知道如何让这个站点打印这些行。你看到的整数0和1不在同一行上。它们都在不同的行上。考虑如下:0110011 \N 1000000……等等。好,当枚举用完元素时抛出异常,但我不确定while循环是否需要,您有嵌套的for循环,它应该会耗尽文件的内容。否?您关于耗尽的说法是正确的。但是,在我删除while循环后,错误仍然存在。错误显然在for循环中,因为代码不会到达它们后面的任何语句。请参阅edit,x.next()在读取一行时,您需要将该行拆分为单独的值。我理解您在这里所做的,这是有意义的。现在的问题是,我接收到一个越界异常。字符串索引超出范围:1。我检查了文件,索引1处有一个字符。但它是一个空格。每个数字都由一个空格分隔。我可能可以使用围绕着这个。
   while(x.hasNext()){
         for(int i = 0; i < n; i++){
             String line = x.next();
             for(int j = 0; j < n; j++){
                 array[i][j] = line.charAt(j) - '0';
                 System.out.printf("%d", array[i][j]);
             }
            System.out.println();
         }
    }