我的代码基于gui,我尝试运行gui,但我没有成功。 公共类SecondFrame扩展了JFrame {
private JPanel contentPane;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
SecondFrame frame = new SecondFrame();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public SecondFrame() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 612, 469);
contentPane = new JPanel();
contentPane.setBackground(Color.BLUE);
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JLabel lblNewLabel = new JLabel("Success !");
lblNewLabel.setFont(new Font("Tahoma", Font.BOLD, 38));
lblNewLabel.setBounds(201, 120, 233, 74);
contentPane.add(lblNewLabel);
JButton btnGenerateGraph = new JButton("GENERATE GRAPH");
btnGenerateGraph.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
try {
FileReader reader = new FileReader("rn.txt");
BufferedReader bufferedReader = new BufferedReader(reader);
String line;
**here i try to convert line that i has read to integer**
while ((line = bufferedReader.readLine()) != null) {
System.out.println(Integer.parseInt(line));
}
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
});
btnGenerateGraph.setFont(new Font("Tahoma", Font.BOLD, 21));
btnGenerateGraph.setBounds(168, 221, 245, 59);
contentPane.add(btnGenerateGraph);
}
}
这是错误: 线程中的异常" AWT-EventQueue-0" java.lang.NumberFormatException:对于输入字符串:" /"
我的rn.txt文件:
29 44 15 17
答案 0 :(得分:0)
读取该行后,尝试替换所有新行字符或回车等,然后执行Integer.parse。
text = text.replace(" \ n","")。replace(" \ r","") ;
答案 1 :(得分:0)
您的文件中似乎有新的行字符,因为它在将其转换为Integer时会出错,因为它无法将特殊字符转换为字符串。
实际找出正在发生的事情的一种方法是首先打印行内容并检查行末尾是否包含空白或特殊字符。 因此,您将能够确定它在何时给出错误。
String line;
**here i try to convert line that i has read to integer**
while ((line = bufferedReader.readLine()) != null) {
System.out.println(line); //Print Content as it is to check at which character you are getting error.
System.out.println(Integer.parseInt(line));
}
同样,您可以在IDE中使用调试器找到它。
如果您在行中实际包含特殊字符或换行符,则可以使用下面的代码删除这些字符。
String line;
**here i try to convert line that i has read to integer**
while ((line = bufferedReader.readLine()) != null) {
line = replaceAll("(\n)+", "");
line = replaceAll("(\r)+", "");
if(line != "" && line!= null){
System.out.println(line); //Print Content as it is to check at which character you are getting error.
System.out.println(Integer.parseInt(line));
}
}
答案 2 :(得分:0)
代码没有错。我使用eclipse创建txt文件。但它没有为我提供.txt的扩展名。所以我手动完成。将粘贴复制到文件夹及其工作。