0

I have two java files in same package. I want to take the updated value of one variable from one file to another. I wrote the following code. In class1.java :-

import javax.swing.JOptionPane;
public class class1 {
    public static String bar = "Yes";
    static int age = 26;
    public static void main(String[] args){
        switch(age) {
            case 25: bar = "world";
                break;
            case 26: bar = "good";
                break;
            case 27: bar = "very";
                break;
            case 30: bar = "hello";
                break;
            default: JOptionPane.showMessageDialog(null,"Please");
                break;
        }
    }
}

In class2.java :-

public class class2 {
    public static void main(String[] args){
        class1 second = new class1();
        System.out.println(second.bar);
    }
}

The problem is that the final value is printed Yes which should not be printed. The output should be good. Please help me.

Uday
  • 5
  • 1

2 Answers2

1
class class1 {

    public String getBar(String age){
        String bar = "Yes";
        switch(Integer.valueOf(age)) {
            case 25: bar = "world";
                break;
            case 26: bar = "good";
                break;
            case 27: bar = "very";
                break;
            case 30: bar = "hello";
                break;
        }
        return bar;
    }
}

public class class2 {
    public static void main(String[] args){
    String age = JOptionPane.showInputDialog("Age Please");
    class1 class1Obj = new class1();
    System.out.println(class1Obj.getBar(age));
    }
}

enter image description here

bigbounty
  • 16,526
  • 5
  • 37
  • 65
  • Thank you for your answer. This is much better way to get the value of _var_ variable. – Uday Jul 12 '20 at 08:33
  • Though your answer is more tricky and better than previous, your answer do not give what exactly the solution is. So, I won't accept it as the answer. Thank you brother and sorry for this. – Uday Jul 12 '20 at 08:40
0

You create a class1 object, but you never run the main method. This means that the section of code never runs, and thus bar remains as "Yes".

In class2 insert second.main(args); before you print second.bar and you will get a good value.

FailingCoder
  • 757
  • 1
  • 8
  • 20