-3

I'm new to Java so I'm practicing with some simple code. I want to create some methods and use Scanner for all of them, but I don't want to declare Scanner every time I create other new methods.

So here is my code. Is this correct? Are there better ways to do this?

import java.util.*;

public class TripPlanner {

    public static final Scanner input = new Scanner(System.in);

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

    public static void Greeting() {
        System.out.println("Welcome to Vacation Planner");
        System.out.print("What is your name? ");
        String  name = input.nextLine();
        System.out.print("Nice to meet you " + name +", where are you travelling to? ");
        String place = input.nextLine();
        System.out.println("Great! " + place + " sounds like a great trip" );
        System.out.println("************");
        System.out.println("\n");
    }
}
user812786
  • 4,302
  • 5
  • 38
  • 50
  • you never want to pass around stateful resources like this ( or database connections ) to multiple methods it makes your entire application an impossible to debug intertwined statemachine. What you want to do is dispatch the acquired data using a strategy pattern like I explain in the duplicate. –  Jul 06 '17 at 17:23

1 Answers1

0

Yes, that will work for different methods in the same thread.

It is important to note, however, that unless you synchronize access to the scanner, you cannot use it in different threads

If you need it in different threads then make one for each thread

Jamal H
  • 934
  • 7
  • 23