Good day, friends. I'm just starting to get acquainted with Java. And then a question came up. There are, in addition to the main method, two more. In one of these two, there is a variable that I need to use in another method, but it does not see it, if I just write it, let's say if (choice = 1) { dir_kor(); } if (choice = 1) { dir_kor(); } Maybe I somehow didn’t ask the question, you forgive me, but I think that it’s understandable Please help)

 `public class Battleship { public static void main(String[] args) { choice_dir(); if (dir = 1) } void choice_dir() { int rm_min = 1; int rm_max = 2; int dir = rm_min + (int) (Math.random() * rm_max); } 

} `

  • Does not see the code where this variable is defined. Could you place all the code you need to understand the question? - Roman C
  • @Ihor Skorobogatko Do not call the variables that way ever. Follow the Java Code Conventions . - Vladimir Glinskikh

2 answers 2

There are two options: put a variable as a class field (for example, private int a) or pass it through a method parameter, i.e. change the method signature a little. Also, you have a common error, you have a check = instead of == (= is an assignment operator, and == is a comparison operator). Correct me if i misunderstand the question

  • public class Battleship { public static void main(String[] args) { choice_dir(); if (dir = 1) } void choice_dir() { int rm_min = 1; int rm_max = 2; int dir = rm_min + (int) (Math.random() * rm_max); } } public class Battleship { public static void main(String[] args) { choice_dir(); if (dir = 1) } void choice_dir() { int rm_min = 1; int rm_max = 2; int dir = rm_min + (int) (Math.random() * rm_max); } } - Igor Skorobogatko
  • It is necessary that I could use the dir variable in other methods. How to be? - Igor Skorobogatko
  • better in a question carry out this code. I wrote, either to render it as a field, or through the argument of the transfer method - Ladence
  • And by the way, in your example you can do it simply: the choice_dir method will return the value that is calculated by the variable dir. Then in main'e there will be a check if (choice_dir () == 1) - Ladence

So it will be easiest to:

 public class Battleship { public static void main(String[] args) { int dir = choice_dir(); if (dir == 1) { //doSomethig... } } int choice_dir() { int rm_min = 1; int rm_max = 2; return rm_min + (int) (Math.random() * rm_max); } } 

As indicated by @Ladence in dir = 1 = need to be replaced with ==.