gpt4 book ai didi

java - 如果用户在 Java 小程序中输入字母而不是数字,则显示警告

转载 作者:行者123 更新时间:2023-12-01 07:28:27 26 4
gpt4 key购买 nike

我正在使用 GUI 在 Java 小程序中编写一个小费计算器应用程序,我的问题是如何确保用户输入字母而不是数字时会弹出错误消息

第一次提问,请多多包涵!谢谢!!!

import objectdraw.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

// Typing in the text field and hitting return adds text to text area.
// Clicking on button erases the text area.
public class TextApplet extends Controller implements ActionListener
{
private static final int ROWS = 1; // rows in TextArea
private static final int COLS = 10; // cols in text field & area

private String amount;
private float number;
private JTextField inField, output; // Input field

private JButton clear, calc;
// button to clear output


public void begin()
{

Container contentPane = getContentPane();
JPanel topPanel = new JPanel(); // prepare text field & label
JLabel inLabel = new JLabel("Bill Cost: ");
inField = new JTextField(COLS);

inField.addActionListener(this);
JLabel topTitle = new JLabel("Tip Calculator", JLabel.CENTER);
JPanel combinePanel = new JPanel();

combinePanel.add ( inLabel );
combinePanel.add ( inField );
JPanel combinePanel1 = new JPanel();
combinePanel1.add ( topTitle );

topPanel.add ( combinePanel1 );
topPanel.add ( combinePanel );


topPanel.setLayout ( new GridLayout ( 3,1) );
contentPane.add(topPanel,BorderLayout.NORTH);

JPanel centerPanel = new JPanel(); // prepare text area & label
JLabel outLabel = new JLabel("Bill + Tip:");
output = new JTextField(COLS);
output.setEditable(false); // Prevent user from wrting in output
centerPanel.add(outLabel);
centerPanel.add(output);
contentPane.add(centerPanel,BorderLayout.CENTER);

JPanel bottomPanel = new JPanel();

// create button
clear = new JButton(" Clear ");
calc = new JButton("Calculate");
calc.addActionListener(this);
clear.addActionListener(this);
bottomPanel.add(calc);
bottomPanel.add(clear);

contentPane.add(bottomPanel,BorderLayout.SOUTH);
validate();
}

// add text to area if user hits return, else erase text area
public void actionPerformed(ActionEvent evt)
{
if (evt.getSource() == calc )
{
amount = inField.getText();
number = ( Float.parseFloat( amount ) );
number = (15*number/100);

output.setText ( Float.toString ( number ) + '$' );
}

else if (evt.getSource() == clear )
{
output.setText("$");
inField.setText("");
}
}
}

最佳答案

您可以使用多种方法来实现这一目标

关于java - 如果用户在 Java 小程序中输入字母而不是数字,则显示警告,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20695228/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com