编写窗体应用程序,安排一个文本框、一个按钮和一个标签,从文本框录入一个数字(0~9),点击按钮将其对应的英文单词(如:zero,one等)显示在标签中 。进一步,扩展数据的范围(如:0~100),如何修改程序实现翻译。(Java实现)
时间: 2024-04-30 08:25:20 浏览: 155
以下是Java实现的代码:
```java
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class NumberToWord extends JFrame implements ActionListener {
private JLabel label;
private JTextField textField;
private JButton button;
public NumberToWord() {
setTitle("数字转英文单词");
setSize(300, 150);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
panel.setLayout(new FlowLayout());
label = new JLabel("请输入0~9之间的数字:");
panel.add(label);
textField = new JTextField(10);
panel.add(textField);
button = new JButton("转换");
button.addActionListener(this);
panel.add(button);
add(panel);
setVisible(true);
}
public void actionPerformed(ActionEvent e) {
String input = textField.getText();
try {
int num = Integer.parseInt(input);
if (num < 0 || num > 100) {
JOptionPane.showMessageDialog(null, "请输入0~100之间的数字!", "错误", JOptionPane.ERROR_MESSAGE);
return;
}
String[] words = {"zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten",
"eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen",
"nineteen", "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety",
"hundred"};
String result;
if (num <= 20) {
result = words[num];
} else if (num < 100) {
int tens = num / 10;
int ones = num % 10;
result = words[18 + tens];
if (ones > 0) {
result += "-" + words[ones];
}
} else {
result = words[0] + " " + words[29];
}
label.setText("英文单词为:" + result);
} catch (NumberFormatException ex) {
JOptionPane.showMessageDialog(null, "请输入数字!", "错误", JOptionPane.ERROR_MESSAGE);
}
}
public static void main(String[] args) {
new NumberToWord();
}
}
```
在这个实现中,我们增加了输入范围的检查,如果输入的数字不在0~100之间,将会弹出错误提示框。
在 actionPerformed 方法中,我们使用一个字符串数组来保存0~100的英文单词。如果输入的数字小于等于20,则直接从数组中获取对应单词,否则按照十位和个位分别处理。
最后,我们使用 label 来显示转换后的英文单词。
阅读全文