带有HashSet的Java中的NullPointerException

时间:2016-07-14 22:11:00

标签: java nullpointerexception

这个程序基本上迭代了问候的hashset集合。问候语存储在名为greeters的hashSet中的manager类中。我要做的是创建一个方法,迭代一个绿色并根据一组变量打印出来(isHappy和greetTimes)。很高兴确定问候语是否会有感叹号,greetTimes确定问候语出现的次数。但是,当我运行allGreet方法时,我不断获得空指针异常。感谢任何帮助:)以下是错误消息的确切文本:

显示java.lang.NullPointerException     在Manager.allGreet(Manager.java:51)

以下是课程:

import java.util.HashSet;
import java.util.*;
/**
 * Class manager
 */
public class Manager
{

/**
 * Constructor for objects of class Manager
 */
public Manager()
{
    HashSet <Object> greeters = new HashSet<Object>(); 
    // add elements to the hash set
    greeters.add("Hola");
    greeters.add("G'Day");
    greeters.add("Ciao");
    for(Object greeter : greeters){
        System.out.println(greeter);
    }
}

/**
 * all the different greetings for the Greeter
 */
public static void main(Object args[]) {
    Manager hi = new Manager();
    hi.allGreet();
}



public String greeting = "Bonjour";
public int greetTimes = 6;
public boolean isHappy = true;
public HashSet greeters;

/**
 * allGreet Method 
 */
public void allGreet() 
{

        if(greetTimes < 0) {
            System.out.println("Invalid number of greetings!");
        }

        else {
            if(isHappy == true){
                for(Object greeter : greeters){
                    System.out.println(greeter + "!");
                }
            }
            else {
                for(Object greeter : greeters){
                    System.out.println(greeter);
                }
            }
        }
    }


}


/**
 * Class Greeter:
 *
 * Hello-world program to demonstrate BlueJ.
 */
class Greeter
{
/**
 * Method that does the work 
 */
public void go()
{
    if(greetTimes < 0) {
        System.out.println("Invalid number of greetings!");
    }
    else {
        if(isHappy == true){
            for (int i = 0; i < greetTimes; i++) {
                System.out.println(greeting + "!"); 
            }
        }
        else {
            for (int i = 0; i < greetTimes; i++) {
                System.out.println(greeting); 
            }
        }
    }
}

public String greeting = "Bonjour";
public int greetTimes = 6;
public boolean isHappy = true;

public Greeter(String greeting, int greetTimes, boolean isHappy)
{
    this.greeting = greeting; 
    this.greetTimes = greetTimes;
    this.isHappy = isHappy;

}

public Greeter()
{
    this.greeting = greeting;
}

/**
 *  main method for testing outside BlueJ 
 */
public static void main(String[] args)
{
    Greeter hi = new Greeter();
    hi.go();
}

public String getGreeting()
{
    return greeting;
}

public void setGreeting(String greeting)
{
    this.greeting =  greeting;
}

public int getgreetTimes()
{
    return greetTimes;
}

public void setgreetTimes(int greetTimes)
{
    this.greetTimes = greetTimes;
}

public boolean getisHappy()
{
    return isHappy;
}

public void setisHappy(boolean isHappy)
{
    this.isHappy = isHappy;
}

}

0 个答案:

没有答案