当我按下" next"时,我得到一个InputMismatchException。按钮。 以下是具有按钮的面板的代码:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class PanelSampleYard extends JPanel
{
private JLabel label;
private DisplaySampleYard display;
int times = 0;
public PanelSampleYard()
{
setLayout(new BorderLayout());
setPreferredSize(new Dimension(200, 125));
label = new JLabel("Green and Grow Mowing Company", SwingConstants.CENTER);
add(label, BorderLayout.NORTH);
display = new DisplaySampleYard();
add(display, BorderLayout.CENTER);
JPanel subpanel = new JPanel();
subpanel.setLayout(new FlowLayout());
JButton next = new JButton("Next");
JButton quit = new JButton("Quit");
next.addActionListener(new Listener1());
quit.addActionListener(new Listener2());
subpanel.add(next);
subpanel.add(quit);
add(subpanel, BorderLayout.SOUTH);
}
private class Listener1 implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
display.next(display.contents(times));
times++;
}
}
private class Listener2 implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
System.exit(0);
}
}
}
面板内显示的代码:
import javax.swing.*;
import java.awt.*;
import java.util.*;
public class DisplaySampleYard extends JPanel
{
private JLabel label;
private JTextField last, first, size, cost, total;
double sum = 0;
int index = 0;
public DisplaySampleYard()
{
setLayout(new GridLayout(5,2));
last = new JTextField("");
add(new JLabel("Last Name:"));
add(last);
first = new JTextField("");
add(new JLabel("First Name:"));
add(first);
size = new JTextField("");
add(new JLabel("Lawn Size:"));
add(size);
cost = new JTextField("");
add(new JLabel("Total Cost:"));
add(cost);
total = new JTextField("");
add(new JLabel("Running Total:"));
add(total);
}
public void next(Customer c)
{
last.setText(c.getLastName()+"");
first.setText(c.getFirstName()+"");
size.setText(c.getSize()+"");
cost.setText(c.getCost()+"");
sum = sum + c.getCost();
total.setText(""+sum);
}
public Customer contents(int index)
{
Scanner infile = new Scanner("greenGrow.txt");
int reps = infile.nextInt();
Customer[] array = new Customer[reps];
for(int x = 0; x<reps; x++)
{
array[x].setLastName(infile.next());
array[x].setFirstName(infile.next());
array[x].setSize(infile.nextInt());
}
return array[index];
}
}
扫描仪正在读取的数据文件包含:
5
Jeffers
Tom
5000
Smith
Sam
10000
Nevar
Tina
15000
Kim
Lisa
20000
Black
Kim
30000
我的代码出了什么问题?提前谢谢!
P.S。还有一些课程,但我认为他们没有引起这个问题
答案 0 :(得分:1)
当您使用Scanner
读取文件时,您应该通过File
类型参数构造,它将扫描指定文件中的值。像:
new Scanner(new File("greenGrow.txt"));
如果按String
构建,Scanner
将扫描指定String