找不到符号 - 变量name1 - TreeSet

时间:2010-07-13 15:50:56

标签: java

在methodB中,我做了一个for循环,其中不显示重复的名称。如果我在methodASet中执行此循环,它将起作用。当我尝试在方法B中执行此操作时,我收到错误消息“找不到符号 - 变量名1”。通常我使用this.nameofthemethodheader();,但我现在知道我不能为TreeSet做这个。有人可以帮助我吗?这是代码。谢谢。请记住,我想将此用于循环,我已经完成了。

public class MyMates  
{

  public MyMates()
  {
    super();    
    names = new TreeSet<String>();  
  }

  public static void methodASet()
  {

    String[] name1 = new String[] {"Amy", "Jose", "Jeremy", "Alice", "Patrick"};
    String[] name2 = new String[] { "Alan", "Amy", "Jeremy", "Helen", "Alexi"};
    String[] name3 = new String[] { "Adel", "Aaron", "Amy", "James", "Alice" };
  }

public static void methodB()
    {


    for (int i = 0; i < name1.length; i++) 
    {
     names.add(name1[i]);
    }
    System.out.println(names);

    for (int i = 0; i < name2.length; i++)
    {
       names.add(name2[i]);
    }   
    System.out.println(names);

    for (int i = 0; i < name3.length; i++)
    {
       names.add(name3[i]);
    }   
    System.out.println(names);


    Dialog.alert("repeated names not selected");
   }

3 个答案:

答案 0 :(得分:3)

name1,name2和name3是局部变量;它们的范围仅限于声明它们的方法。在这个范围之外,他们没有任何意义。

答案 1 :(得分:2)

在方法之外声明String [] name1等,然后只在方法中放入“name1 = new String []”等。

  String[] name1 = null;
  String[] name2 = null;
  String[] name3 = null;

  public static void methodASet()
  {

    name1 = new String[] {"Amy", "Jose", "Jeremy", "Alice", "Patrick"};
    name2 = new String[] { "Alan", "Amy", "Jeremy", "Helen", "Alexi"};
    name3 = new String[] { "Adel", "Aaron", "Amy", "James", "Alice" };
  }

答案 2 :(得分:1)

好的,试试这个:(我写的只是为了做工作......在我看来,这是一个糟糕的代码)

import java.util.Set;
import java.util.TreeSet;

public class MyMates {

private static String[] name1 = null;
private static String[] name2 = null;
private static String[] name3 = null;
private static Set<String> names;

public MyMates() {
    methodASet();
    names = new TreeSet<String>();
}

public static void methodASet() {

    name1 = new String[]{"Amy", "Jose", "Jeremy", "Alice", "Patrick"};
    name2 = new String[]{"Alan", "Amy", "Jeremy", "Helen", "Alexi"};
    name3 = new String[]{"Adel", "Aaron", "Amy", "James", "Alice"};
}

public static void methodB() {

    for (int i = 0; i < name1.length; i++) {
        names.add(name1[i]);
    }
    System.out.println(names);

    for (int i = 0; i < name2.length; i++) {
        names.add(name2[i]);
    }
    System.out.println(names);

    for (int i = 0; i < name3.length; i++) {
        names.add(name3[i]);
    }
    System.out.println(names);
}

public static void main(String[] args) {
    MyMates polop = new MyMates();
    MyMates.methodB();
}
}

打印:

[Alice,Amy,Jeremy,Jose,Patrick]

[Alan,Alexi,Alice,Amy,Helen,Jeremy,Jose,Patrick]

[Aaron,Adel,Alan,Alexi,Alice,Amy,Helen,James,Jeremy,Jose,Patrick]