有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java Get方法返回null

所以我试着用Java编写一个挂程序,当我尝试使用get方法获取输出变量时,它返回null。首先设置一个Scanner对象,然后将字符串设置为用户输入的值,然后使用set方法将字符串设置为新变量,最后使用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) 个答案

  1. # 1 楼答案

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