Reputation: 1
So I tried to make a Hanger program in Java, and when I try to get to output a variable using a get method, it returns null. I first set up a Scanner object, then I set a String to the value the user inputs, then I use a set method to set the String to a new variable, finally, I call that new variable using the get method. It returns null, and I don't know why.
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?");
}
}
Upvotes: 0
Views: 505
Reputation: 3682
It should be this.word=new_word
in your setWord method of Hanger class
Upvotes: 4