簡體   English   中英

從文本文件添加數組值並打印它們

[英]Adding array values from a text file and printing them

我的C驅動器中有一個名為new.txt的文本文件,我正嘗試使用以下程序將Java程序將此文件的內容放入多維數組。

package square;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.Reader;
import java.nio.Buffer;
import java.util.Arrays;
import java.util.Scanner;

public class Square {

    public static void main(String[] args) {
        String a[][] = new String[4][4];
        try {
            FileReader fr = new FileReader("C://new.txt");
            Scanner scanner=new Scanner(fr);
            for (int i = 0; i < 5; i++) {
                for (int j = 0; j < i; j++) {
                    a[i][j] = scanner.next();
                }
            }
            System.out.print(Arrays.deepToString(a));
            scanner.close();
        } 

        catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }


    }
}

在這里,當我嘗試運行該程序時,出現以下異常。

Exception in thread "main" java.util.NoSuchElementException: No line found
    at java.util.Scanner.nextLine(Unknown Source)
    at square.Square.main(Square.java:20)

當我更改a[i][j] = scanner.next(); a[i][j] = scanner.nextInt(); 並將數組類型更改為int m會引發以下異常。

Exception in thread "main" java.util.InputMismatchException
    at java.util.Scanner.throwFor(Unknown Source)
    at java.util.Scanner.next(Unknown Source)
    at java.util.Scanner.nextInt(Unknown Source)
    at java.util.Scanner.nextInt(Unknown Source)
    at square.Square.main(Square.java:20)

請讓我知道我要去哪里哪里以及如何解決。

我的文本文件的內容是。

#####
#####
#####
#####
…..

默認的分隔符是空格。由於您沒有任何空格,因此第一個讀取的字符串本身是##### \\ n ##### \\ n ##### \\ n #####。還有很多其他問題,例如此問題中的循環錯誤。您可以嘗試以下更改並查看是否適合您,否則請提供更多說明

String a[][] = new String[5][5];
Scanner scanner=new Scanner(fr).useDelimiter("");
for (int i = 0; i < 5; i++)
   for (int j = 0; j < 5; i++) {
       if(scanner.hasNext("\n"))
           scanner.next();
       a[i][j] = scanner.next();
      }

 System.out.print(Arrays.deepToString(a));
        scanner.close();

這里的問題很簡單。 首先查看您的文本文件:

#####
#####
#####
#####
…..

在這里,我們有5個標記(4個'#####'和1個'.....')。 看一下:next()函數上的http://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html

NoSuchElementException - if no more tokens are available
IllegalStateException - if this scanner is closed

因此,在掃描程序讀取了最后一個令牌(即“ .....”)之后,就不再有可用的令牌了。

這是我建議的解決方案:

import java.io.FileNotFoundException;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.Scanner;

public class Square {

    public static void main(String[] args) {
        String a[][] = new String[5][5];
        try {
            FileReader fr = new FileReader("new.txt");
            Scanner scanner=new Scanner(fr);
            ArrayList<String> l = new ArrayList<String>();
            while(scanner.hasNext())
            {
                l.add(scanner.next());
            }
            for(int i = 0; i < l.size(); ++i)
            {
                String toSplit = l.get(i);
                String[] splitted = toSplit.split("");
                for(int j = 0; j < splitted.length; ++j)
                {
                    a[i][j] = splitted[j];
                }
            }
            scanner.close();
        } 

        catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        // test the result
        for(int i = 0; i < a.length; ++i)
        {
            for(int j = 0; j < a[i].length; ++j)
            {
                System.out.println(a[i][j]);
            }
        }
    }
}

請注意:最后兩行為空,因為最后一個令牌具有3個字符。 因此a [4] [3]和a [4] [4]將為空。

前面的注解:

請檢查您的String數組的二維。 目前是

new String[4][4];

並允許存儲16個值(4x4)。 循環中使用的代碼看起來像您期望更多的值。 因此我將數組增加到

new String[5][5];

現在來回答您的問題:

在外部規避5的固定值for -loop我以一取代它while -loop:

int i=0;
while (scanner.hasNextLine()) {
  String line = scanner.nextLine();
  String[] separatedChars = line.split("(?!^)");
  for (int j = 0; j < 5; j++) {
    a[i][j] = separatedChars[j];
  }
  i++;
}
System.out.print(Arrays.deepToString(a));
scanner.close();

相反,僅使用內下一for -loop我使用scanner.nextLine()讀取的完整產品線,然后分裂它。 然后將結果用於填充給定的數組。 四行5x#輸出

[[#, #, #, #, #], [#, #, #, #, #], [#, #, #, #, #], [#, #, #, #, #], [null, null, null, null, null]]s

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM