我收到一个错误,提示我尚未初始化 buffer.write(variable);
行中的firSTLine、secondLine 和thirdLine 变量,其中变量为firstLine、secondLine 和thirdLine。直到我在 variable == JOptionPane.showInputDialog("Enter name"); 周围添加
行。有什么方法可以在保留我添加的代码的同时处理此错误吗?while(number == null || number.equals(""))
后,此错误才出现。我的代码中的
import java.awt.Graphics;
import javax.swing.JOptionPane;
import java.io.*;
import java.io.FileWriter;
public class CreateData {
public static void main(String[] args)
{
JOptionPane.showMessageDialog(null,
"this program writes payroll data",
"Welcome", JOptionPane.PLAIN_MESSAGE);
Write();
}
static void Write()
{
try {
String firstLine, secondLine, thirdLine, number = " ";
File check = new File("payroll.txt");
FileWriter file;
if(check.exists())
file = new FileWriter("payroll.txt", true);
else
file = new FileWriter("payroll.txt");
BufferedWriter buffer = new BufferedWriter(file);
int size, count = 1;
while(number == null || number.equals(""))
{
number = JOptionPane.showInputDialog("how many records?");
}
size = Integer.parseInt(number);
do {
while(number == null || number.equals(""))
{
firstLine = JOptionPane.showInputDialog("Enter name");// prompts for input and displays "Enter Name"
}
while(number == null || number.equals(""))
{
secondLine = JOptionPane.showInputDialog("Enter hours");
}
while(number == null || number.equals(""))
{
thirdLine = JOptionPane.showInputDialog("Enter wage");
}
buffer.write(firstLine);//write firstLine variable to payroll.txt file
buffer.newLine();
buffer.write(secondLine);
buffer.newLine();
buffer.write(thirdLine);
buffer.newLine();
count++;
}while(count <= size);
buffer.close();//closes the data writing stream to payroll.txt file
JOptionPane.showMessageDialog(null, "data processed",
"Result", JOptionPane.PLAIN_MESSAGE );//display message "data processed"
System.exit(1);
}
catch (IOException e) { System.out.println(e); }
}
}
最佳答案
这一行
String firstLine, secondLine, thirdLine, number = " ";
等于
String firstLine;
String secondLine;
String thirdLine;
String number = " ";
所以你需要初始化你的firstLine、secondLine、thirdLine:
String firstLine = "";
String secondLine = "";
String thirdLine = "";
String number = " ";
关于Java初始化变量错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28651230/