【问题标题】:Get method returns null获取方法返回 null
【发布时间】:2014-08-08 23:21:30
【问题描述】:

所以我尝试用 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?");
}


}

【问题讨论】:

    标签: java methods null


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-09-02
      • 1970-01-01
      • 1970-01-01
      • 2019-04-18
      • 1970-01-01
      • 2013-11-19
      相关资源
      最近更新 更多