我遇到的问题是程序显示如下
1 请输入名称 红色 请输入此活动的价格
红色
请输入此活动的价格
40
请输入此活动的日期
请输入此活动可用的门票数量。
完全跳过日期。如何编辑我的代码以便我可以正确输入数据。
任何提示和建议都会很棒。我做错了什么?
谢谢
我的代码是
案例1:
char ans;
do{
Event event = new Event();
out.println("Please Enter the name ");
event.setEvent(input.next());
input.nextLine();
do {
try {
out.println("Please Enter the price of this event\n");
event.setprice(input.nextDouble());
} catch (InputMismatchException e) {
out.println("Please Enter the price of this event\n");
}
input.nextLine();
} while (!input.hasNextDouble());
out.println("Please Enter the date of this event\n");
event.setdate(input.next());
out.println("Please enter the amount of tickets available for this event.\n");
event.setavailability(input.nextInt());
out.println("Please enter");
event.setvenue(input.next());
Events.add(event);
out.println("Would you like to add a new event?");
String answer = input.next();
ans = answer.charAt(0);
while (ans== 'y');
out.println (Events.get(0));
break;
}
答案 0 :(得分:-1)
以下代码显示 JFrame ,其中包含 JLabel , TextField &一个 JButton 。如果输入一个整数,它将显示 JOptionPane ,表示...已接受。否则它会显示 JOptionPane 并显示错误消息。我想你可能希望处理 NumberFormatException 。您应该更新您的问题,否则它将被拒绝。以下代码处理 NumberFormatException 。
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class ExceptionTest extends JFrame implements ActionListener {
private JTextField jtf;
public ExceptionTest() {
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel jp = new JPanel();
add(jp);
this.setSize(300, 200);
JLabel lbl = new JLabel("Enter price");
jp.add(lbl);
jtf = new JTextField(9);
jp.add(jtf);
JButton btn = new JButton("Click to check");
btn.addActionListener(this);
jp.add(btn);
this.setLocationRelativeTo(null);
}
public static void main(String[] args) {
new ExceptionTest().setVisible(true);
}
@Override
public void actionPerformed(ActionEvent arg0) {
try {
Integer.parseInt(jtf.getText());
JOptionPane.showMessageDialog(this, "Number accepted");
} catch (NumberFormatException e) {
JOptionPane.showMessageDialog(this,
"This text field accept only integers", "Invalid Input",
JOptionPane.ERROR_MESSAGE);
}
}
}