嘿所以我寫了一些代碼來讀取文本文件的內容,做一些比較並輸出1或0到2D數組中。這裏是一個片段使用異常處理從主要方法打印2D數組
import java.io.*;
import java.util.*;
public class readFile
{
private String path;
//declare variables for visited and link
//String inputSearch1 = "Visited";
//String inputSearch2 = "Link";
String word;
public readFile(String pathname)
{
path = pathname;
}
//open the file and read it and search each line of the file for 'Visited' and 'Link'
public String[] OpenFile() throws IOException
{
FileReader fr = new FileReader(path);
BufferedReader lineReader = new BufferedReader(fr);
int numberOfLines = readLines();
String[] lineData = new String[numberOfLines];
int i;
for(i=0; i<numberOfLines; i++)
{
lineData[i] = lineReader.readLine();
}
lineReader.close();
return lineData;
}
//allows the file to be parsed without knowing the exact number of lines in it
int readLines() throws IOException
{
FileReader file_to_read = new FileReader(path);
BufferedReader bf = new BufferedReader(file_to_read);
String aLine;
int numberOfLines = 0;
while((aLine = bf.readLine()) != null)
{
numberOfLines++;
}
bf.close();
return numberOfLines;
}
int outLinks;
int inLinks;
String bLine;
String[] searchStrings() throws IOException
{
FileReader ftr = new FileReader(path);
BufferedReader bf2 = new BufferedReader(ftr);
int numberOfLines = readLines();
//String bLine;
String[] parseLine = new String[numberOfLines]; //array to store lines of text file
int[][] linkMatrix = new int[outLinks][inLinks]; //2d array to store the outLinks and inLinks
int i;
for(i=0; i<numberOfLines; i++)
{
parseLine[i] = bf2.readLine();
int j, k;
for(j=0; j<outLinks; j++)
{
for(k=0; k<inLinks;k++)
{
if(bLine.startsWith("Visited") && equals(bLine.startsWith("Link")))
{
linkMatrix[outLinks][inLinks] = 1;
}
else
{
linkMatrix[outLinks][inLinks] = 0;
}System.out.println(Arrays.deepToString(linkMatrix));
}//System.out.println();
}
}bf2.close();
return parseLine;
}
我現在想輸出這些來自主要方法,但每次我運行它的時候,我得到的是文本文件,並沒有二維矩陣的內容。
import java.io.IOException;
public class linkStatistics
{
public static void main(String[] args) throws IOException
{
// TODO Auto-generated method stub
//read file
String fileName = "C:\\Users\\Ikemesit\\Documents\\Lab_4.txt";
try
{
readFile file = new readFile(fileName);
//String[] lines = file.OpenFile();
String[] lines = file.searchStrings();
int i;
for(i=0;i<lines.length;i++)
{
System.out.println(lines[i]);
//System.out.println(lines2[i]);
}
}
catch(IOException e)
{
System.out.println(e.getMessage());
}
}
} 任何幫助,將不勝感激!謝謝。
首先,請張貼的編譯代碼。 'bLine'的聲明被註釋掉了,但是這個變量仍然在你的代碼中使用,所以這段代碼不會通過編譯。 – Eran 2014-11-24 16:11:48
我發佈的是一個片段,我不認爲我需要發佈我的整個代碼。 bLine在其他地方初始化。我應該發佈整個事情嗎? – user2035796 2014-11-24 16:18:48
'bLine'的初始化可能是您的問題的根源。如果它爲空,你的循環會拋出NullPointerException。根據部分代碼很難弄清楚你的問題。 – Eran 2014-11-24 16:21:27