I'm starting out programming with java and I'd like to make some games and various other things which require changing variables, especially integers. Let me give you an example.
int Score = 0;
if(coinCollected = 1){
int Score = 1
}
Now of course this is going to return 'int Score has already been defined', or whatever, but I don't want it to say that, since I want to REdefine the variable. I've tried #Override before the if statement and that didn't work, either. Does anyone know what to do?
I think you want to update the value, if so, you don't need to re-define.
int Score = 0;
if(coinCollected == 1){
// change the value
Score = 1;
}
You do not want to redefine the variable. You want to assign it a new value.
So simply remove the "int" from the second occurrence, so it looks like score = 1.
By the way, Java style conventions state variable names start with lowercase.
so you don't have to define Score again..
your code should look like this
int Score = 0;
if(coinCollected == 1){
Score = 1
}
if(coinCollected = 1)
In the above statement you are assigning the value of 1 to variable named coinCollected, but thats NOT what you want to do, u want to compare the value 1 with the value of the variable named coinCollected.
Eg:
if(coinCollected == 1)
Now in the below code you are re-declaring the variable Score.
{
int Score = 1
}
Corrected code:
int Score = 0;
if(coinCollected == 1){
Score = 1
}
Use a different scope, or reuse the existing score or preferably using a different name.
{
int score = 0;
} // scope of Score has ended.
if(coinCollected == 1) {
int score = 1;
}
Related
I'm using a for loop as a form of validation check to make sure the input for the variable stScore is a number over 0 and under or equal to 100, example shown here, if the input isn't correct, the score parameter will be shown as 0:
for(int i = 0; i < 3; i++)
if ((stScore[i] > 0 && stScore[i] <= 100))
score[i] = stScore[i];
else
score[i] = 0;
My question is if there is any way to display a string (to say something like error!) in place of that 0 instead? Of course at the base of things you can't have an int array include a string, but I was wondering if there is a workaround for this.
Thanks
A workaround would be to ascribe some magic meaning to a particular int value that would never otherwise occur in your data. E.g., declare a constant:
private static final int INVALID_SCORE = -1;
Use it both when assigning:
if ((stScore[i] > 0 && stScore[i] <= 100))
score[i] = stScore[i];
else
score[i] = INVALID_SCORE;
And when printing:
System.out.println(score[i] != INVALID_SCORE ? score[i] : "Invalid score!");
The disadvantage is that it will cause problems if you forget to treat the value specially in later code that uses the data.
No, unfortunately you cannot :(. But we usually don't use 0 as an error code. In these situations I use Integer.MIN_VALUE to indicate an error.
So your code will be like this:
for(int i = 0; i < 3; i++)
if ((stScore[i] > 0 && stScore[i] <= 100))
score[i] = stScore[i];
else
score[i] = Integer.MIN_VALUE;
I suggest you not to use 0. Because 0, when it is an exit code, it usually means "OK". In C++, the main method returns 0 when the program exits with no errors. Alternatively, Integer.MAX_VALUE can be used as well.
For more readable code, you can declare a constant called ERROR:
final int ERROR = Integer.MIN_VALUE;
The best option would be to set any invalid inputs to -1. Then on output you could have an if statement the checks for the error value (-1) and outputs an appropriate error message.
It's bad practice to mix types in any sort of collection; avoid it whenever possible.
throw new IllegalArgumentException("your score is below zero");
That would seem to be appropriate
I need help on how to minus out the value in my object which is (25) when a random number (num) has been generated. I have written my code below but there seem to be a problem in my last line.
StickBag s1 = new StickBag(25);
int randNum = 1 + (int)(Math.random()*2);
int num = 1 + (int)(Math.random()*11);
for(int i = 0; i < 25 ; i++)
{
if(randNum == 1)
{
System.out.println("Computer player 1 chooses " + num + " sticks. ");
StickBag = StickBag - num;
}
For e.g. If a random number that is generated is 5 , then the total value in my object (25) will minus the value that was generated randomly (5) and therefore my object will then have the value 20 in it
I hope i have made myself clear
The trouble with the line
StickBag = StickBag - num;
is that StickBag is the name of a class. You actually want to refer to an instance of that class.
In your program, you have an instance of StickBag called s1. Therefore, what you probably want to write is something like this:
s1.stickCount = s1.stickCount - num;
That's with the assumption that stickCount is a public attribute of the class StickBag, and that it's what gets initialized to the value 25 when you do new StickBag(25).
Let me suggest that you rename s1 to something more expressive, such as gameBag. That might not suit your particular concept, but whatever it is, try to use words rather than single letters and numbers.
Also, num is pretty vague and could be renamed to something more specific, such as playerMove. And you might want to use the -= operator to perform the subtraction. If you were to apply all three of my suggestions, the line would look like this:
gameBag.stickCount -= playerMove;
If stickCount is private and you have to access its value with getStickCount() and set its value with setStickCount(), you would write the following.
gameBag.setStickCount(gameBag.getStickCount() - playerMove);
Note that in this case you can't use the -= operator. (Some programming philosophies insist on using getters/setters and others don't. The debate isn't germane to this question and you can find plenty of material on it elsewhere.)
I am currently making a text adventure game in Java, but I have come across a problem:
I need the value of a String variable to change each time the value of a particular int variable changes.
I want the program to perform this task (then continue where it left off) each time the value of an int variable changes:
if (enemyposition == 1) {
enemyp = "in front of you";
}
else if (enemyposition == 2) {
enemyp = "behind you";
}
else if (enemyposition == 3) {
enemyp = "to your left";
}
else if (enemyposition == 4) {
enemyp = "to your right";
}
else {
enemyp = "WOAH";
}
Thanks! :D
You could make the code much shorter using an array.
String[] message = {"WOAH", // 0
"in front of you", // 1
"behind you", // 2
"to your left", // 3
"to your right"}; // 4
enemyp = (enemyposition > 0 && enemyposition < 5) ? message[enemyposition] :
message[0];
The question you're asking sounds like it might be answerable by creating a class to hold the enemyposition integer. Add a "setter" method to your class to set the integer. You can write your setter method so that when the integer is set, it also sets up a string. Then write a "getter" method to retrieve the string. That's one common way of making sure two variables change together.
public class EnemyPosition {
private int enemyposition;
private String enemyp;
public void setPosition(int n) {
enemyposition = n;
enemyp = [adapt your code to set this based on the position]
}
public String getEnemyp() {
return enemyp;
}
}
I'm sure there are a lot of details missing, but you get the idea. Then instead of int enemyposition in the rest of your code, use EnemyPosition enemyposition = new EnemyPosition(), and use the setPosition method instead of assigning to it.
That's not the only solution (an array or Map that maps integers to strings may be good enough), but it's one OOP way to do things.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 months ago.
Improve this question
I'm reading Head First Java and an exercise is confusing me a little bit. The Original instructions of the exercise are irrelevant, however, the point is to be able to solve it with out just compiling the code and running it, which would just spit out the answer. I am quite confused and am trying to play the debugger and go step by step each line of code and see what is happening. I have added my comments to the code to make sure I am understanding it. Just need help understanding for example what the count is at a specific point and such. Here is the original code, with one line added myself, which i've noted. Some of the lines I will note which I don't understand the best.
**Update: So I gave the best understanding on my code. Questions I have about certain lines are in the comments. If anyone can maybe do a step by step approach of what happens would make it a lot more understandable. Thank you all for your help in advance. I am new to StackOverFlow so hopefully this was the correct way of asking a question.
public class Mix4
{
int counter = 0; //This is setting the variable counter to 0.
public static void main (String[] args)
{
int count = 0; //This is setting the variable count to 0.
Mix4[] m4a = new Mix4[20];//This is initializing an array of 20 m4a objects to null.
int x = 0; //This is setting the variable x to 0;
while ( x < 9 )
{
m4a[x] = new Mix4(); //This actually creates the m4a object at array index 0.
m4a[x].counter = m4a[x].counter + 1;
//This line is very confusing. How can you use a dot operator on a variable?
//I am saying variable because as stated above there is a int counter = 0;
count = count + 1; //This increments the variable count. Why do this though?
count = count + m4a[x].maybeNew(x);
//The count variable again is being implemented but this time it calls the
// maybeNew method and it is passing a 0 as as the argument? Why do this?
x = x + 1; // x is being incremented.
System.out.println(count + " " + m4a[1].counter);
//What is this printing and when does this print?
}
public int maybeNew(int index)
{
if (index < 5)
{
Mix4 m4 = new Mix4(); //Creating a new object called m4.
m4.counter = m4.counter + 1;
//Same question about this from the code of line stated above using dot
//operators on variables.
return 1; //Where does 1 be returned to? I thought you can only have one
//return statement per method?
}
return 0; // I thought only 1 return statement? I have no idea what these return
// statements are doing
}
}
}
m4a[0].counter = m4a[x].counter + 1;
//This line is very confusing. How can you use a dot operator on a variable?
//I am saying variable because as stated above there is a int counter = 0;
m4a is an array of Mix4 objects. You can call object methods or properties(variables) using the . operator
count = count + m4a[x].maybeNew(x);
//The count variable again is being implemented but this time it calls the
// maybeNew method and it is passing a 0 as as the argument? Why do this?
maybeNew() return an int. You are trying to increase the count by whatever number maybeNew(x) returns. x is the value of m4a[0], if x = 0.
System.out.println(count + " " + m4a[1].counter);
//What is this printing and when does this print?
This prints at end of your program. It prints the counter value for the Mix4 object at index 1 in the m4a array
return 1; //Where does 1 be returned to? I thought you can only have one
//return statement per method?
}
return 0; // I thought only 1 return statement? I have no idea what these return
// statements are doing
First of all, a method may or may not return a value. In you method, you want it to return an int. So when you call it here count = count + m4a[x].maybeNew(x);, it like saying, whatever number maybeNew(x) returns, add that to count.
Your first return 1 is inside of a conditional statement. If the condition is satisfied, return 1, else return 0
int x = 0; //This is setting the variable x to 0;
You got this part right
Now inside while loop in the 1st iteration x = 0;
Mix4[] m4a = new Mix4[20];
This again as you correctly guesses is just defining of an array. Simply putting it is a group of 20 reference of type Mix which woould point to the actuall Object of type Mix. Now you have to assign these objects to the references which is what we are doing in the while loop.
m4a[x] = new Mix4();
Here in 1st iretartion we are doing m4a[0] = new Mix4(); so the element at index 0 is initialized.
m4a[0].counter = m4a[x].counter
Here we are simply accessing the counter of the actual object and assigning value to it.
How can you use a dot operator on a variable?
First if all m4a[0] has been initialized. Next thing you need to know is acess modifieer. If you look at the statement
int counter = 0;
No access modifer is specified which means it has default access modifier. Now for default access modifier visibilty of a variable is in the same class and same package(No need of getter/setter methods).
Also note that counter is an instance variable(not local variable) and instance variables are assigned default values(for int it is 0, for String it is null and so on...)
Try to debug the code step by step with this basic understanding.
Where does 1 be returned to? I thought you can only have one
return statement per method?
You may have have one return statement for one branch in your function, its not restricting to have one one return statement per function, its should be only one return statement for one logic path. Like :
public int DoStuff(Foo foo) {
if (foo == null) return 0;
...
return 1; // any thing
}
m4a[0].counter = m4a[x].counter + 1;
//This line is very confusing. How can you use a dot operator on a variable?
//I am saying variable because as stated above there is a int counter = 0;
m4a is an array ofMix4Class objects. You can call object methods or properties using the . operator.
From Using Objects
Code that is outside the object's class must use an object reference or expression, followed by the dot (.) operator, followed by a simple field name, as in:
objectReference.fieldName
System.out.println(count + " " + m4a1.counter);
//What is this printing and when does this print?
From System.out.println()
Prints an Object and then terminate the line. This method calls at first String.valueOf(x) to get the printed object's string value, then behaves as though it invokes print(String) and then println().
It will print the count value, and counter value for the Mix4 object at index 1 in the m4a array.
Your code as you have shown above will not compile for two reasons:
You have the System.out.printlninside the while loop; this will result in a NullPointerException as when the compiler gets to m4a[1].counter the m4a[1] object has not been created. Only m4a[0] has been created. Alternatively you can leave this line where it is but change it to m4a[0].counter
You have the maybeNew(int index) method declaration inside main; this is mostly likely just a mistake with your curly brackets but just so you know you can't declare a method inside another method; main is a method and so you must declare maybeNewoutside it but call it from within main
public class Mix4 {
int counter = 0;
public static void main (String[] args) {
int count = 0;
Mix4[] m4a = new Mix4[20];
int x = 0;
while (x < 9) {
m4a[x] = new Mix4();
m4a[x].counter = m4a[x].counter + 1;
count = count + 1;
count = count + m4a[x].maybeNew(x);
x = x + 1;
// System.out.println(count + " " + m4a[0].counter);
}
System.out.println(count + " " + m4a[1].counter);
}
public int maybeNew(int index)
{
if (index < 5)
{
Mix4 m4 = new Mix4();
m4.counter = m4.counter + 1;
return 1;
}
return 0;
}
}
I'm trying to make a tetris game for android to help learn game programming for android. My goLeft/Rights break right when the button is pressed, the code for going left is in a class separate of the fields int array, and the list parts array. The fields array is accessed by a referenced variable (TetrisWorld tetrisworld;). While part list array is public so accessed through a variable(part) code for which is in the goLeft() code. It breaks at: if(tetrisworld.fields[x][part.y] != 0) Code for left:
public void goLeft() {
int x = 0;
for(int i = 0; i < 4; i++) {
TetrisParts part = parts.get(i);
x = part.x - 1;
if(tetrisworld.fields[x][part.y] != 0) {
noleft = true;
break;
}
}
if(noleft == false) {
for(int i = 0; i < 4; i++) {
TetrisParts part = parts.get(i);
part.x--;
}
}
}
The code for the fields int array:
int fields[][] = new int[WORLD_WIDTH][WORLD_HEIGHT];
WORLD_WIDTH and WORLD_HEIGHT are both static final ints, width being 9 and height being 19
I've tried putting if(tetrisworld.fields[0][0] == 0) and it still crashes so I don't think it has to do with the variables. Also It doesn't go out of bound even if I haven't added the code to check for that yet because I have the teroid spawning around x = 5 and since I can't go left/right once there's not a chance of that happening
I've tried moving the goLeft/Right methods to the gamescreen class which has a "world = TetrisWorld();" and it still bugs out at the same spot
UPDATE:
Ok just adding:
tetrisworld != null
to the first if statement fixed it, my question now is, why did it fix it? Why can't I move without this check? It clearly isn't null cause as far as I know; it's fully responsive now.
But an easier way to have solved this which is SOOOO easy is changing fields to static... then access it lika so: TetrisWorld.fields so my updated code is:
public void goLeft()
{
noleft = false;
for (int i = 0; i < 4; i++)
{
part = parts.get(i);
if (part.x - 1 < 0 || TetrisWorld.fields[part.x - 1][part.y] != 0)
{
noleft = true;
break;
}
}
if (noleft == false)
{
for (int i = 0; i < 4; i++)
{
part = parts.get(i);
part.x--;
}
}
}
Looks like you are hitting IndexOutOfBoundsException.
When you are doing x = part.x - 1;, your x variable can become lesser tan zero, thus your code will act like if(tetrisworld.fields[-1][part.y] != 0
It looks like you're getting a java.lang.NullPointerException when trying to access the array in tetrisworld. In the line you mention there are several ways that this could occur:
if(tetrisworld.fields[x][part.y] != 0) {
tetrisworld could be null.
The fields member of tetrisworld could be null.
The second array that you're looking up by using tetrisworld.fields[x].
The value of part could be null.
Having a quick look through your source code it looks to me like you never initialise tetrisworld, either at declaration using:
TetrisWorld tetrisworld = new TetrisWorld();
Or at some other point which is certain to have happened before your goLeft() method is called.
Ok I believe I found the answer, referencing: http://en.wikipedia.org/wiki/Null_Object_pattern
Apparently java will throw an NPE if you don't check for it first if you have a null reference? Is there any way to initialize it without doing a TetrisWorld tetrisworld = new TetrisWorld(); because it's already created in a different class so i get a thousand errors, an actual stack overflow! lul... Still not 100% positive. Please comment to verify and possibly suggest a better way to go about this.