我有这个代码,它有一些创建文件的方法,将数据添加到文件,然后用扫描仪读取文件。 我的问题是我想让它一次运行我的三个方法,但它会停止 在方法二,并没有读取文件与readFile()方法
createFile();
addResponses(file);
readFile(file);
我不能把这三个一起运行。它不读取文件。但是,如果我采取 像这样的其他方法
//createFile();
//addResponses(file);
readFile(file);
然后读取文件方法有效。
我希望你明白我的问题。我的代码有问题吗?
import java.io.*;
import java.util.Formatter;
import java.util.Scanner;
import javax.swing.JOptionPane;
public class Main {
static Formatter f;
static String sträng = " ";
static BufferedWriter output;
static File file;
static int nummer = 1;
static int counter = 0;
static private StringBuffer strBuff;
static InputStream is;
static FileWriter fw;
/**
* @param args the command line arguments
*/
public static void main(String[] args) throws Exception {
createFile();
addResponses(file);
readFile(file);
}
public static int addResponse() {
if (nummer == 6) {
try {
output.close();
} catch (IOException ex) {
JOptionPane.showMessageDialog(null, ex.getMessage());
}
System.exit(0);
}
sträng = JOptionPane.showInputDialog("Numbers 1-5 to number " + nummer");
try {
return Integer.parseInt(sträng);
} catch (NumberFormatException f) {
return 6;
}
}
public static File createFile() {
try {
file = new File("numbers.txt");
f = new Formatter(file);
f.close();
} catch (SecurityException se) {
System.err.println("You dont have write access to this file");
System.exit(1);
} catch (Exception ex) {
System.err.println("Error opening or creating file");
System.exit(1);
}
return file;
}
public static void readFile(File x) {
try {
x = new File("numbers.txt");
Scanner in = new Scanner(x);
while (in.hasNextLine()) {
System.out.println(in.nextLine());
}
in.close();
} catch (Exception e) {
System.out.println(e.getMessage());
e.printStackTrace();
}
}
public static void addResponses(File f) throws IOException {
try {
fw = new FileWriter(f, true);
output = new BufferedWriter(fw);
int x = addResponse();
if (nummer == 1) {
output.write(String.format("%s%10s\n", "Rating", " Frequency"));
}
while (x != -1) {
if (x > 0 && x < 6) {
output.write(String.format("%s%10s\n", nummer, sträng));
nummer++;
} else {
JOptionPane.showMessageDialog(null, "Input only numbers between 1-5");
}
x = addResponse();
}
output.close();
} catch (IOException io) {
JOptionPane.showMessageDialog(null, "Wrong");
}
}
}
答案 0 :(得分:0)
在玩完代码之后,我发现在你的addResponse()方法中,你添加了System.exit(0);因此,节奏计划正在终止。我将其更改为返回-1,它似乎正在工作。
顺便说一句,这是一个非常糟糕的编码实践,每个方法都应该单独做其他方法的东西。在你的情况下,一切都是如此整合,很难根除问题。我建议你看看一些编码惯例。这就是addResponse()方法应该如何工作:
public static File createFile() {
try {
file = new File("numbers.txt");
f = new Formatter(file);
f.close();
} catch (SecurityException se) {
System.err.println("You dont have write access to this file");
System.exit(1);
} catch (Exception ex) {
System.err.println("Error opening or creating file");
System.exit(1);
}
return file;
}