首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >Get方法返回null

Get方法返回null
EN

Stack Overflow用户
提问于 2014-08-09 07:21:30
回答 1查看 410关注 0票数 0

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

代码语言:javascript
运行
复制
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?");
}


}
EN

回答 1

Stack Overflow用户

发布于 2014-08-09 07:22:58

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

票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/25213625

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档