+ 1

Why won't my code work?

import java.util.Scanner; public class Operators { Scanner read = new Scanner(System.in); public String op = read.next(); } public class Program { public static void main(String[] args) { if (op.equals("hi")) { System.out.println("hello"); } } } It says that op is not defined.

23rd Jan 2023, 10:07 PM
Evan Xiang
4 Answers
+ 6
In Java, every class is a separate compilation object. They don't have visibility over the internals of the other class, unless you grant them access. You have this error because the "op" variable is in the Operators class, and your Program class is unaware of that. But another problem is, the code inside the Operators class is is just executed and forgotten. You don't have any methods and you don't have a constructor. So even if you instantiate an Operators object with the new keyword, nothing will happen. Because you haven't marked your variables as "static", they are assigned and then discarded by Java and garbage collected. There are couple of different ways to solve it. - move the code in the Operators class inside a static method which returns the result. - move the code from the Operators class to the Program class, preferably inside a method, it can be in the main method too. - mark both of the variables inside the Operators class as static, then you can reference them in your Program class as: Operator.op - write a constructor in the Operators class where you assign the value to the op field. Then you can create an instance of Operators in the Program class and refer to its field. Either of these solutions can fix your program, but you probably need to understand a bit more about how Java works, to see what difference they make. Keep learning! :)
24th Jan 2023, 5:41 AM
Tibor Santa
Tibor Santa - avatar
+ 1
How do you get information from one class into the main class?
23rd Jan 2023, 10:48 PM
Ausgrindtube
Ausgrindtube - avatar
0
What do you mean?
24th Jan 2023, 2:58 AM
Evan Xiang
0
Thank you so much!
24th Jan 2023, 9:20 PM
Evan Xiang