Answer the question
In order to leave comments, you need to log in
How to use a variable entered from the console in main() (Java)?
Good day,
I need to use the "name" variable entered from the console, both in main() and in other methods, provided that the input is registered in NOT main().
Thank you in advance!
import java.util.Scanner;
public class Test {
public static void nameInput() {
Scanner sc = new Scanner(System.in);
System.out.println("What is your name?");
String name = sc.next();
sc.close();
}
public static void main(String args[]) {
nameInput();
System.out.print(name);
}
Answer the question
In order to leave comments, you need to log in
The most obvious way is to put the variable in the appropriate scope.
import java.util.Scanner;
public class Test {
private static String name;
public static void nameInput() {
try (Scanner sc = new Scanner(System.in)) {
System.out.print("What is your name? ");
Test.name = sc.next();
}
}
public static void main(String args[]) {
Test.nameInput();
System.out.println(Test.name);
}
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question