Get方法返回null

时间:2014-08-08 23:21:30

标签: java methods null

所以我尝试在Java中创建一个Hanger程序,当我尝试使用get方法输出变量时,它返回null。我首先设置一个Scanner对象,然后我将String设置为用户输入的值,然后我使用set方法将String设置为一个新变量,最后,我使用get方法调用该新变量。它返回null,我不知道为什么。

import java.util.Scanner;

public class Hanger
{
public String word;
public Hanger(){}
public void setWord(String new_word)
{
    new_word = word;
}
public String getWord()
{
    return word;
}

public static void main(String[] args)
{
    Scanner input_names = new Scanner(System.in);
    Scanner input_word = new Scanner(System.in);
    Hanger word1 = new Hanger();
    System.out.println("Please enter Player 1's name.");
    String name1 = input_names.nextLine();
    System.out.println("Please enter Player 2's name.");
    String name2 = input_names.nextLine();
    System.out.println("Are your names " + name1 + " and " + name2 + "?");
    String names_correct = input_names.nextLine();
    switch (names_correct)
    {
        case "no":
        {
            System.out.println("Please enter Player 1's name.");
             name1 = input_names.nextLine();
            System.out.println("Please enter Player 2's name.");
             name2 = input_names.nextLine();
            System.out.println("Are your names " + name1 + " and " + name2 + "?");
             names_correct = input_names.nextLine();
        }
        case "No":
        {
            System.out.println("Please enter Player 1's name.");
            name1 = input_names.nextLine();
            System.out.println("Please enter Player 2's name.");
            name2 = input_names.nextLine();
            System.out.println("Are your names " + name1 + " and " + name2 + "?");
            names_correct = input_names.nextLine();
        }
        default:
        {
            break;
        }

    }
    System.out.println("Let's begin! " + name1 + ", please type a word that " + name2 + " will try to guess.");
    String input_word1 = input_word.nextLine();
    word1.setWord(input_word1);
    System.out.println("Is " + word1.getWord() + " correct?");
}


}

1 个答案:

答案 0 :(得分:4)

在Hanger类的setWord方法中应该是this.word=new_word