对于两个乒乓球队进行比赛,各出三人。甲队为a,b,c三人,乙队为x,y,z三人。已抽签决定比赛名单。有人向队员打听比赛的名单。a说他不和x比,c说他不和x,z比,请编程序找出三队赛手的名单。
原来的想法是,做四个字符串,其中前面三个为条件字符串,第四个为动态生成的字符串。通过第四个字符串和前面三个字符串的对比,得出最终结果。执行上述代码,提示无法从静态上下文中引用非静态变量str4。
请教下,如果一个字符串要连接非静态变量,应如何操作。
public class Exer18
{
static char[] m = {'a','b','c'};
static char[] n = {'x','y','z'};
String str1 = "a VS x";
String str2 = "c VS x";
String str3 = "c VS z";
        String str4;
public static void main(String[] args)
{
for (int i = 0; i < m.length; i++)
{
for (int j = 0; j < n.length; j++)
{
str4 = m[i] + " VS " + n[j];
if (str1 == str4 || str2 == str4 || str3 == str4)
{
continue;
}
else
System.out.println(str4);
}
}
}
}
执行上述代码,提示无法从静态上下文中引用非静态变量str4。

解决方案 »

  1.   

    你的那4个字符串都必须是静态变量,加static就ok了
      

  2.   

    1.将字符串声明成静态变量
    2.使用局部变量,将变量在main里面声明
    3.用对象访问自己的成员变量。
      

  3.   

    LZ应该用
    if (str1.equals(str4) || str2.equals(str4) || str3.equals(str4))
    来进行比较
      

  4.   

    如果一个字符串要连接非静态变量like this:public class Exer18
    {
        static char[] m = {'a','b','c'};
        static char[] n = {'x','y','z'};
        public static void main(String[] args)
        {
         String str1 = "a VS x";
            String str2 = "c VS x";
            String str3 = "c VS z";
            String str4;
            for (int i = 0; i < m.length; i++)
            {
                for (int j = 0; j < n.length; j++)
                {
                    str4 = m[i] + " VS " + n[j];
                    if (str1 == str4 || str2 == str4 || str3 == str4)
                    {
                        continue;
                    }
                    else
                        System.out.println(str4);
                }
            }
        }
    }
      

  5.   

    如果坚持把这四个字符串放在原位,那就这样:static String str1 = "a VS x";
    static String str2 = "c VS x";
    static String str3 = "c VS z";
    static String str4;或者把它们放到main()中定义(6楼那样),这时不需要加static。
      

  6.   

    定义str4的时候放在main()方法里面就不需要定义成static类型了
    但是你比较用==是不对的,应该用equals方法。
      

  7.   

    当然不一样了,你仔细看清楚了么?你是定义了函数外的属性,会提示Cannot make a static reference to the non-static field str4错误。而我是在函数中使用的局部变量,不会出错,执行也是正确的。评论之前,先执行一下可以么?所发的这个和我的完全一样啊