0

How can I access a value from a different method?

I have something like this: two booleans (adv1, adv2) declared globally, initialized as false. method1() { //code if (something) { adv1 = true; //code } if (something else) { adv2 = true; //code } //They will never be true at the same time } method2 () { if (adv1){ //some code } if (adv2) { //some code } System.out.print("lala"); } Now, it seems that the ifs in method2 are not accessed at all because it only prints lala at the end, ignoring the //some code entirely. How can I keep the changes on the advs?

8th Feb 2018, 1:08 PM
Lăbonţu Marius-Andrei
Lăbonţu Marius-Andrei - avatar
2 odpowiedzi
+ 6
According to your description, if the two booleans are declared in the global scope, your code should work fine. If method1 is called prior to method2, and the conditions work properly, the boolean values should be altered. E.g. #include <iostream> bool x = 0, y = 0; void method1() { x = 1; y = 1; } void method2() { if (x) std::cout << "Hello"; if (y) std::cout << "World"; std::cout << "Test"; } int main() { method1(); method2(); return 0; } Perhaps you can provide the code for further inspection?
8th Feb 2018, 2:14 PM
Hatsy Rei
Hatsy Rei - avatar
0
public static void deuce() { System.out.print("Cine a punctat?"); score = scorer.nextLine(); switch (score) { case "p1": advP1 = true; System.out.println("Avantaj jucatorul 1"); System.out.print("Cine a punctat?"); score = scorer.nextLine(); switch (score) { case "p1": setPoints(); break; case "p2": advP1 = false; System.out.println("Egaliate"); deuce(); break; default: System.out.println("Ati introdus un jucator gresit! Mai incercati."); break; } case "p2": advP2 = true; System.out.println("Avantaj jucatorul 2"); System.out.print("Cine a punctat?"); score = scorer.nextLine(); switch(score) { case "p2": setPoints(); break; case "p1": advP2 = false; System.out.println("Egalitate"); deuce(); break; default: System.out.println("Jucator inexistent. Mai incercati."); break; } } //scorer.close(); } public static void setPoints() { if (advP1 = true) { if (ptP1 > 5 && Math.abs(ptP1 - ptP2) < 2) { tiebreaker(); } else while (ptP1 <= 6 && Math.abs(ptP1 - ptP2) > 2) { ++ptP1; System.out.println("Scorul este: " + ptP1 + " - " +ptP2); initialize();
8th Feb 2018, 3:32 PM
Lăbonţu Marius-Andrei
Lăbonţu Marius-Andrei - avatar