A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© 邱成 中级黑马   /  2012-9-8 00:06  /  1093 人查看  /  1 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

本帖最后由 邱成 于 2012-9-8 07:41 编辑

有三张卡,其中两张银卡,一张黄金卡,放在把背面提供给竞猜者来猜,让竞猜者随机三
选一,用图形用户界面设竞猜过程,下面是我写的代码可是提示找不到符号,为什么?
import java.awt.*;
import java.awt.event.*;
class Guess extends Frame
{
        Label label1,label2;
        Button buttonbegin;
        String[] strs ={"1","2","3"};
        Guess(String s)
        {
                setTitle(s);
                setLayout(new FlowLayout());
                buttonbegin=new Button("开始猜测或重新猜测");
                buttonbegin.addActionListener(new B());
                label1=new Label("           请点击按钮开始猜测         ");
                label2=new Label("看看您是否猜对了!",Label.CENTER);
                label2.setBackground(Color.red);
                Button[] b=new Button[strs.length];
                for(int i=0;i<strs.length;i++)
                {
                        b=new Button("卡片"+strs);
                        b.addActionListener(new B());
                }
                label1.setBackground(Color.red);
                add(buttonbegin);
                add(label1);
                for(int i=0;i<strs.length;i++)
                add(b);  
                add(label2);
                setBackground(Color.green);
                setBounds(500,200,220,150);
                setVisible(true);
        }
        class B implements ActionListener
        {
                public void actionPerformed(ActionEvent e2)
                {
                        if(e2.getSource()==buttonbegin)
                        {
                                int num=(int)(Math.random()*3);
                                label1.setText("           请选择卡片进行猜测 ");
                        }
                        else if(e2.getSource()==b[num]) //编译报错
                        {
                                label2.setText("恭喜您,答对了!");
                        }
                }
        }        
}
public class YellowGeuss
{
        public static void main(String args[])
        {
                Guess guess=new Guess("黄金竞猜");
        }
}

评分

参与人数 1技术分 +1 收起 理由
创出一片辉煌 + 1 赞一个!

查看全部评分

1 个回复

倒序浏览
兄弟!你还是没有把局部变量和成员变量的作用域和生命周期没搞明白! 首先:
else if(e2.getSource()==b[num]) //编译报错   
                        {
                                label2.setText("恭喜您,答对了!");
                        }
其中的b按钮的对象数组定义在Guess的构造方法中,内部内只能访问外部类的成员变量,而构造方法中的变量为局部变量,只作用在构造方法中,
其次:"num"此变量是在  if(e2.getSource()==buttonbegin)
                        {
                                int num=(int)(Math.random()*3);
                                label1.setText("           请选择卡片进行猜测 ");
                        }
这段代码中声明并定义的它的作用域是在if语句中有作用,
你试试把: Button[] b=new Button[strs.length];
的声明不分放在成员位置上,实例部分放在构造方法中,
再把   int num=(int)(Math.random()*3);
的声明部分放在   actionPerformed(ActionEvent e2)方法中的局部变量,赋值不分放在if语句中!
回答有点乱,希望LZ把变量的作用域好好理一理!
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马