+ 1
Scanner and inputs across several methods
Perhaps it's not a good idea to have more than one method taking inputs from the user. If that's the case I may yet have to refactor my codebase again. That said, when one is taking user inputs across more than one method do you have to declare a Scanner variable in each method that you are taking user input? Does each Scanner variable have to have different name or, because they are hidden inside their particular methods, does that really matter? Thoughts? Suggestions? https://code.sololearn.com/cFIYQfSx38iR/#java
5 Respostas
0
If you declare variable in method it is local variable of this method and will be visible only in its local scope (so it makes no sense to declare it as static because only that method could work with it anyway). To set variable visible to all methods of a class you should declare it in class scope like that:
class DecoderRing {
static Scanner sc = new Scanner(System.in); //<<----- here it is
public static void main(String[] args) {
....
+ 2
@Jeth I agree, I'll have to actually sit down and do some studying on OOP. When I tried to make a static Scanner in main() I got errors trying to run the code over the System.in in Scanner(System.in) during the declaration and initialization. I successfully got Scanner to work from main() by removing the static from its declaration and passing the Scanner variable as an argument to the other methods. Now I'm probably breaking six rules from sundown for OOP doing so, but I can see already that I have much to learn.
+ 2
So this makes the Scanner variable global across the class? I try y up avoid globals as much as possible, but sometimes a global does make sense. I'll need to make a decision here. Thanks for your help.
+ 1
You can declare static Scanner variable in your main class and use it across all methods of this class. Java is all about OOP so you should learn how to use OOP to solve your tasks, it will help you a lot when you start to write more complex code.
+ 1
This variable is not actually global, it will not be visible in classes in another packages unless you set it with "public" or "protected" modifier. Also you can set it as "private" and it will not be visible in other classes at all. There is nothing bad in setting class scope variable, in many cases this can be the only right way to work with data. It is not recommended to use such global variables as in PHP where you can declare variable visible in whole code in all classes and functions. Closest Java analogue to it is "public static" variable and even in this case it will be linked with its class and should be obviously imported in other classes to be able to use it. You can view source code of Java classes (Scanner for example) and see how much class variables it has. Note that it is a professional code of professional programmers.