编辑:对于偶然发现这篇文章的人,我通过使用 ArrayList 而不是普通数组来解决我的问题 - 这样做减少了我的代码的三分之一,并使其大部分可重用。感谢所有在下面提供帮助的人。这是我为那些正在寻找的人更新的代码的链接:http: //pastebin.com/Yh3LVu2H
该程序旨在读取文件的行并将它们输出到两个数组 xAxis 和 yAxis - iv 将其拆分为两个文件,因为我将使用 ScreenSizes.java 来构建 GUI。
我在 "System.out.println("X: " + xAxis[index]);" 这一行遇到了异常
ScreenSizes.java 中的代码:
package screensizes;
import java.io.*;
import java.util.Scanner;
import java.util.Arrays;
public class ScreenSizes{
public String filePath = "/Users/jonny/Documents/UNI/ScreenSizes/xy.txt";
public static void main(String[] args) throws FileNotFoundException
{
ScreenSizes obj = new ScreenSizes();
obj.run();
}
public void run() throws FileNotFoundException {
GetScreens data = new GetScreens(filePath);
int noLines = data.countLines();
int[] xAxis = data.getData('x');
int[] yAxis = data.getData('y');
int index = 0;
while(index<noLines){
System.out.println("X: " + xAxis[index]);
index++;
}
}
}
来自 GetScreens.java 的代码
package screensizes;
import java.io.*;
import java.util.Scanner;
import java.util.Arrays;
public class GetScreens
{
public int lines;
public String filePath = "";
public int[] x = new int[lines];
public int[] y = new int[lines];
public GetScreens(String aFileName) throws FileNotFoundException{
fFile = new File(aFileName);
filePath = aFileName;
try
{
processLineByLine();
countLines();
}
catch(FileNotFoundException fnfe)
{
System.out.println(fnfe.getMessage());
}
catch(IOException ioe)
{
System.out.println(ioe.getMessage());
}
}
public final void processLineByLine() throws FileNotFoundException {
//Note that FileReader is used, not File, since File is not Closeable
Scanner scanner = new Scanner(new FileReader(fFile));
try {
while ( scanner.hasNextLine() ){
processLine( scanner.nextLine() );
}
}
finally {
//ensure the underlying stream is always closed
//this only has any effect if the item passed to the Scanner
//constructor implements Closeable (which it does in this case).
scanner.close();
}
}
public int[] getData(char choice){
if(choice == 'x'){
return x;
}
else{
return y;
}
}
public void processLine(String aLine){
//use a second Scanner to parse the content of each line
Scanner scanner = new Scanner(aLine);
scanner.useDelimiter("x");
if ( scanner.hasNext() ){
for(int i=0; i<lines; i++){
x[i] = scanner.nextInt();
y[i] = scanner.nextInt();
}
}
else {
log("Empty or invalid line. Unable to process.");
}
}
public int countLines(){
try
{
BufferedReader reader = new BufferedReader(new FileReader(filePath));
while (reader.readLine() != null) lines++;
reader.close();
}
catch(FileNotFoundException fnfe)
{
System.out.println(fnfe.getMessage());
}
catch(IOException ioe)
{
System.out.println(ioe.getMessage());
}
return lines;
}
// PRIVATE
public final File fFile;
private void log(Object aObject){
System.out.println(String.valueOf(aObject));
}
private String quote(String aText){
String QUOTE = "'";
return QUOTE + aText + QUOTE;
}
}