对于两个乒乓球队进行比赛,各出三人。甲队为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。
原来的想法是,做四个字符串,其中前面三个为条件字符串,第四个为动态生成的字符串。通过第四个字符串和前面三个字符串的对比,得出最终结果。执行上述代码,提示无法从静态上下文中引用非静态变量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。
2.使用局部变量,将变量在main里面声明
3.用对象访问自己的成员变量。
if (str1.equals(str4) || str2.equals(str4) || str3.equals(str4))
来进行比较
{
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);
}
}
}
}
static String str2 = "c VS x";
static String str3 = "c VS z";
static String str4;或者把它们放到main()中定义(6楼那样),这时不需要加static。
但是你比较用==是不对的,应该用equals方法。