0

How to use variable in class in main method?

package org.opentutorials.javatutorials.inheritance; import java.util.Scanner; class CalculatorX { static Scanner sc = new Scanner(System.in); static int left = sc.nextInt(); static int right = sc.nextInt(); public void sum() { System.out.println(left + right); } public void avg() { System.out.println((left + right) / 2); } } class SubtractCalculatorX extends CalculatorX { public void sub() { System.out.println(left - right); } } public class CalculatorDemoX { public static void main(String[] args) { SubtractCalculatorX c1 = new SubtractCalculatorX(); //System.out.printf(left + " + " + right); c1.sum(); c1.avg(); c1.sub(); } } I want to make // part possible. However, It seems that java cannot bring left and right value to main method. How can I use left and right value?

17th Oct 2019, 2:18 AM
PReiZ
PReiZ - avatar
3 Answers
+ 2
A minimal example for your reference. class Test { static int x = 39; } public class Program { public static void main(String[] args) { System.out.print(Test.x); } }
17th Oct 2019, 2:26 AM
Hatsy Rei
Hatsy Rei - avatar
+ 2
Try using public class calculator! Or try calling left and right by calculator object Calculator c = new Calculator (); System.out.println(c.left+"+"+right);
17th Oct 2019, 2:24 AM
Chirag Kumar
Chirag Kumar - avatar
+ 1
thanks! You both helped me a lot!
17th Oct 2019, 2:31 AM
PReiZ
PReiZ - avatar