...

View Full Version : Decrement A variable from another class



anonymous9
03-29-2012, 07:03 PM
How would I grab variable from another class and add decrementer.
I tried this but it didnt work.
int quarters1=CasinoGame.quarters;
quarters1--;

Fou-Lu
03-29-2012, 07:35 PM
Not enough information.
Is this within a scope to be decremented? Also, int is a primitive value, and as such quarters1 may equate to CasinoGame.quarters (assuming a static int) initially, but they are not the same variable. Decrementing quarters1 will have no effect on CasinoGame.quarters. You need to use an Integer if that is the behaviour you want.

anonymous9
03-29-2012, 10:06 PM
How would I make it so that the variable is shared with all classes I create in one java project. I'm trying to decrement the same variable from different classes.

Fou-Lu
03-30-2012, 12:03 AM
How would I make it so that the variable is shared with all classes I create in one java project. I'm trying to decrement the same variable from different classes.

If its publicly accessible member, you can decrement it wherever you would like by direct access. If its retrieved, you need to treat it as an object by using the Integer class.

anonymous9
03-30-2012, 04:04 PM
Ok I got that working but when I try to pass the CasinoGame.quarters into method inside SlotMachine Class I get an error. Can anyone rewrite this correctly so I can see how it is done.
Heres both classes



import java.util.Scanner;

public class CasinoGame {

public static int quarters;

public static void main(String[] args) {
int quarters;

System.out.println("Please enter how many quarters are in the jar: ");
Scanner keyboard = new Scanner(System.in);
quarters = keyboard.nextInt();

}
}




public class SlotMachine {

public static void main(String[] args) {

public void Slot1(int Casino.quarters){
CasinoGame.quarters--;

}
}
}public class SlotMachine {

public static void main(String[] args) {

public void Slot1(int Casino.quarters){
CasinoGame.quarters--;

}
}
}

Fou-Lu
03-30-2012, 05:43 PM
You cannot do that as Casino.quarters is a value, not a definable variable as a parameter.
Slot1 should take no parameters.



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum