我的任务是通过文本字段输入20个数字,然后使用while循环输出平均值、中位数和总和。我应该能够自己弄清楚while循环,但是我不能让文本字段将数字输入到数组中。请帮帮忙,这是我到目前为止的代码:
import java.applet.Applet;
import java.awt.Graphics;
import java.awt.*;
import java.awt.event.*;
public class whileloopq extends Applet implements ActionListener
{
Label label;
TextField input;
int[] numArray = new int[20];
int num;
public void init ()
{
Label label = new Label("Enter numbers");
TextField input = new TextField(5);
add(label);
add(input);
input.addActionListener(this);
}
public void actionPerformed (ActionEvent ev)
{
int num = Integer.parseInt(input.getText());
int index = 0;
numArray[index] = num;
index++;
input.setText("");
}
public void paint (Graphics graf)
{
graf.drawString("Array" + numArray, 25, 85);
}
}任何帮助都将不胜感激。
发布于 2012-08-13 03:26:10
在actionPerformed()中,您试图从类文件input.setText("");中读取数据
但是在init()中,您没有初始化该字段,而是创建并添加到小程序局部变量
TextField input = new TextField(5);所以类字段是窃取null。将其更改为
input = new TextField(5);发布于 2012-08-13 03:17:48
(在假设这是一份家庭作业的前提下,以书面形式回答。)
您知道如何从字符串解析整数,就像您在使用Integer.parseInt时所展示的那样,但是您调用它是为了将整个20个字符解析为一个整数。您需要对每个字符分别进行解析。
我建议使用for循环和String#substring将输入文本分成几个长度为1的字符串。
或者,您可以围绕一个空字符串拆分输入文本,然后遍历结果数组(请注意,数组中的第一个字符串将是空的),但另一种方法更可能是Java新手所期望的方法,因此您必须在这里使用您的判断。
发布于 2021-05-27 13:57:13
import java.awt.*;
public class frame4array extends Frame
{
Checkbox c1[];
TextField t1[];
int i;
frame4array(String p)
{
super(p);
c1=new Checkbox[2];
t1=new TextField[2];
for(i=0;i<2;i++)
{
t1[0]=new TextField();
t1[0].setBounds(200, 50, 150, 30);
t1[1]=new TextField();
t1[1].setBounds(200, 80, 150, 30);
c1[0]=new Checkbox("Singing");
c1[0].setBackground(Color.red);
c1[0].setBounds(430,200,120,40);
c1[1]=new Checkbox("Cricket",true);
}
for(i=0;i<2;i++)
{
add(t1[i]);
add(c1[i]);
}
setFont(new Font("Arial",Font.ITALIC,40));
}
public static void main(String s[])
{
frame4array f1=new frame4array("hello");
f1.setSize(600,500);
f1.setVisible(true);
}
}https://stackoverflow.com/questions/11925016
复制相似问题