简体   繁体   中英

How do I use a scanner across multiple classes?

How can I use my Scanner user_input across multiple classes? I have read a few articles, but apparently I am missing something. I even tried following a few other stackoverflow questions, and the result is below:

import java.util.Scanner;

public class HelloWorld{
    public static final Scanner user_input = new Scanner(System.in);

    public static void main(String []args){
        String test1 = user_input.next();
        System.out.println("Test 1: " + test1);
    }
}

class TestClass{
    public static void test_method(){
        String test2 = HelloWord.user_input.next();
        System.out.println("Test 2: " + test2);
    }
}

If someone could help me, I would truly appreciate it.

PS I am new to Java, have background in Python.

From @ferdz comment, something like this would be better:

import java.util.Scanner;

public class HelloWorld {
    public static final Scanner user_input = new Scanner(System.in);

    public static void main(String[] args) {
        String test1 = user_input.next();
        System.out.println("Test 1: " + test1);

        // These two lines actually instantiate the TestClass below,
        // we pass in the Scanner as a parameter (user_input), and 
        // then it gets used in the test_method internally.
        TestClass testClass = new TestClass(user_input);
        testClass.test_method();
    }

    private static class TestClass {
        public void test_method(Scanner scanner) {
            String test2 = scanner.next();
            System.out.println("Test 2: " + test2);
        }
    }
}

Your only problem is you have missed spelt the word world in your second class.

So change:

String test2 = HelloWord.user_input.next();

to:

String test2 = HelloWorld.user_input.next();

and it should work

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM