theretrogamer theretrogamer - 2 months ago 11
Java Question

Scanner input string appearing as null java

My code is here:

package test1;
import java.util.*;
public class Test1 {
public static String input;

public Test1(){
Scanner answer = new Scanner(System.in);
String test = answer.next();
}
public static void initializeConstructor(){
Test1 input = new Test1();


}

public static void begin () {
System.out.println("type:");

initializeConstructor();

System.out.println(input);


}

public static void main(String[] args) {
begin();
}


}

I am really new to learning java, my idea is that I can call the constructor to to start the scanner and it will spit back at me what I just typed. I am doing this so I can understand more about constructors in java. However when I run the following program, it just gives me "null". Like I said, i am preety new, so it may be a dumb question but any response would be very appreciated. Thank you in advance.

Answer

Because input is null (never assigned), change

String test = answer.next();

to

input = answer.next();

and your code will work. But input is static (it shouldn't be in real code, not if you're setting it in a constructor).