所以,我把它初始化为一个数组对象,当我去初始化单个对象时,它不会给它们一个值
/*
-A java program GUI for Food to allow user to type the food
*/
public class Catagorygui extends JFrame implements ActionListener{
//attributes
JPanel panel;
JButton button;
JFrame frame;
JLabel item;
JTextField item1;
JLabel cost;
JTextField cost1;
JLabel percentused;
JLabel name;
JTextField name1;
JLabel paidupfront;
JTextField paidupfront1;
public Appartment2 g=new Appartment2();
private static String rec=" ";
private JTextField [] upfront=new JTextField[g.getPeople().size()];//must initialize
private JTextField [] percent=new JTextField[g.getPeople().size()];
private JLabel [] usernames=new JLabel[g.getPeople().size()];//for loop that gives them values
private int a;
public Catagorygui (){
g.addPerson("Ali");
g.addPerson("Kacie");
for(int i=0;i<a;i++)
{
usernames[i]=new JLabel("poop");//somehow not initializing it
percent [i]=new JTextField(10);
upfront [i]=new JTextField(10);
percent[i].addActionListener(this);
}
System.out.println(g.getpeople().get(0).getName());//ali
System.out.print(usernames[0]);//SAYS INDEX OUT OF BOUNDS, should say'poop'
//
a=g.getpeople().size();
答案 0 :(得分:2)
for (int i=0; i<a; i++)
是的,继续i < a
进行迭代,但是a
是什么?你在哪里初始化它?任何int
基元类型在Java中都具有默认值0
。所以0 < 0
总是假的,没有迭代。
答案 1 :(得分:0)
a=g.getpeople().size();
应该在for
循环
答案 2 :(得分:0)
你几乎就在那里,只是一些变数......
for循环没有被执行,因为 a 没有被初始化(或者它是,但是在构造函数的末尾......)只是在进入之前移动变量a的赋值。 for循环而不是错误必须消失! 的 A = g.getpeople()大小(); 强>
public Catagorygui (){
g.addPerson("Ali");
g.addPerson("Kacie");
a = g.getpeople().size(); // move up to here
for(int i=0;i<a;i++)
{
usernames[i]=new JLabel("poop");//somehow not initializing it
percent [i]=new JTextField(10);
upfront [i]=new JTextField(10);
percent[i].addActionListener(this);
}
System.out.println(g.getpeople().get(0).getName());//ali
System.out.print(usernames[0]);//SAYS INDEX OUT OF BOUNDS, should say'poop'
//