我在尝试将数组列表中的单词输出到屏幕上的文本字段时遇到问题。每当我运行程序并在收件箱字段中输入几个单词并单击分析按钮时,什么都不会输出,有什么想法吗?
import javax.swing.*;
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
import java.util.ArrayList;
import java.util.Iterator;
public class SApplet extends Applet implements ActionListener {
TextField input,output;
Label label1;
Button b1, b2;
JLabel lbl;
String Word1;
String wordArrayList[];
public void init(){
label1 = new Label("Please enter your text: ");
add(label1);
label1.setBackground(Color.orange);
label1.setForeground(Color.black);
input = new TextField(20);
add(input);
output = new TextField(20);
add(output);
b1 = new Button("Analyze");
b2 = new Button("Reset");
add(b1);
add(b2);
b1.addActionListener(this);
b2.addActionListener(this);
setBackground(Color.orange);
}
public void actionPerformed(ActionEvent e){
try{
String a = null;
ArrayList<String> wordArrayList = new ArrayList<String>();
if (e.getSource()== b1)
{
Word1 = input.getText();
for(String word : Word1.split(" ")) {
wordArrayList.add(word);
}
Iterator<String> word = wordArrayList.iterator();
if (word.hasNext()) {
// output.setText(word.next());
// System.out.println(word.next());
a += word.next();
}
while (word.hasNext()) {
a += ", " + word.next();
output.setText(a);
// System.out.println(a);
}
}
if(e.getSource() == b2)
input.setText("");
output.setText("");
}
catch(NumberFormatException a){
lbl.setForeground(Color.red);
lbl.setText("Invalid Entry!");
}
}
}
最佳答案
你的问题就在这里。
if(e.getSource() == b2)
input.setText("");
output.setText("");
您可能打算写这个。
if(e.getSource() == b2) {
input.setText("");
output.setText("");
}
但是因为您省略了花括号,所以空白了 output
每次此方法运行时都会发生,而不仅仅是触发事件的按钮是 b2
.
关于java - 数组列表不会输出。 Java小程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21666870/