Difference between += and ++ in Java - java

I have a global variable that I modify in three different methods. It starts at 0, one method adds by 3, the next one by 2 and the last one by 1. They are all related to a button of their own.
When I click the "plus 1" button, the counter remains at 0 and I need another push to get it to 1. Interestingly, if I start with the other two buttons the counter acts accordingly but if I click my "plus 1" button again, it needs two pushes and acts weird like if it was holding the add...
public void addThreeForTeamB(View view) {
displayForTeamB(scoreTeamB += 3);
}
public void addTwoForTeamB(View view) {
displayForTeamB(scoreTeamB += 2);
}
public void addOneForTeamB(View view) {
displayForTeamB(scoreTeamB ++);
}
So that's the way it is managed, the cool thing is that when I change the last method to a "scoreTeamB += 1" it acts as it should, just adding without conflict.
My question is about the difference between this two operators to better understand the reason behind the slight discrepancy generated when using this 2 operators on the same variable.

scoreTeamB++ returns the previous value of the variable (before it was incremented). += returns the value that was assigned to the variable.
If you replace scoreTeamB++ with ++scoreTeamB or with scoreTeamB +=1 you'll get the new (incremented) value of the variable.

To make this code work as you expect, you should use prefix ++ operator instead of postfix one. Prefix ++ operator(as well as -- operator, apparently) returns incremented value, while postfix operator ++ returns value of variable before increment.
Those may be implemented like this:
public static Integer prefixIncrement(Integer value) {
value = value + 1;
return value;
}
public static Integer postfixIncrement(Integer value) {
Integer returnValue = new Integer(value);
value = value + 1;
return returnValue;
}

Related

Adding one to the set of numbers in the array Java

public class Test
{
public static int addOne(int[] numb)
{
for(int i=0;i<numb.length;i++){
System.out.println(numb[i]+1);
int result = numb[i];
}
return (numbers.length);
}
}
Main:
public class Main
{
public static void main(String[] args)
{
int[] numO = {2,2,4,4,6};
System.out.println(Test.addOne(numO)); /
}
}
Output:
3,3,5,5,7,5
I was trying out arrays in java as I am starting to learn arrays, I set five numbers in the array and using a for loop, wanted to add the numbers in the array by 1, e.g. Array containing (1,2,3) would be (2,3,4) and outputting the total number 9, instead of 2,3,4 and a random number. How can I achieve this?
You are never actually changing the value contained within the numb array, what you are doing is taking the existing value and adding outputting it with 1 added to it
System.out.println(numb[i] + 1);
To change the value you must increment the value outside
numb[i]++;
System.out.println(numb[i]);
That should solve your problem of not retaining the changed value in the array. However there is another error that I can see that would prevent you from outputting the correct result value. By doing result + numb[i]; you are preforming an operation but not setting the result variable equal to anything. To set it add to the value it already contains you would do result = result + numb[i] or more properly result += numb[i]
Hope this helps!

Change the value of a variable each time another variable changes

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.

recursive function called with different values

I have a recursive function like this:
public static int h(int n) {
if (n == 0) {
return 0;
}
if (n == 1) {
return 1;
} else {
//variable value is a fixed one.
i = value % 2;
return h(n - h(i) - 1) + h(n - 2);
}
}
Suppose the value of variable value is even at this time.Then if I call the function with h(12) I want to know how the function works?
In this case what I want to happen is evaluate
h(12)=h[12-h(0)-1]+h(10)
=h(11)+h(10)
={h(11-h(0)-1)+h(9)}+{h(10-h(0)-1)+h(8)}
={h(10)+h(9)}+{h(9)+h(8)}
Here when evaluating h(11)+h(10) does the function first finish h(11) and get a value for that before starting with h(n-2) which is this case h(10).
If it first finish h(11) then finally it has to reach n==0 or n==1 case.Then by the time it reaches wouldn't h(n-2) be h(-2) or h(-1).
How can I store the initial function call value of 12 and when it reaches h(n-2) to call as h(10) and then make that part to evaluate as h(8),h(6)..
Each function call stores its own copy of arguments. So, call to h(11) won't change n in the first call (h(12)).
Expressions in Java are evaluated from left to right. This means that the call h(11) would finish before h(10) is called from h(12). However, in this case this is not important, since the result would be the same either way.

How to breakdown a method and process it [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I am preparing for an exam next week, and I decided to look for some exam questions online for better preparation.
I came across this question and the answer is c. But I really want to know how or the step by step process to answer to answer a question like this. The part where I got stuck is trying to logically understand how a int m = mystery(n); How can a number equal a method? Whenever I get to a question like this is their anything important I should breakdown first?
private int[] myStuff;
/** Precondition : myStuff contains int values in no particular order.
/*/
public int mystery(int num)
{
for (int k = myStuff.length - 1; k >= 0; k--)
{
if (myStuff[k] < num)
{
return k;
}
}
return -1;
}
Which of the following best describes the contents of myStuff after the
following statement has been executed?
int m = mystery(n);
(a) All values in positions 0 through m are less than n.
(b) All values in positions m+1 through myStuff.length-1 are
less than n.
(c) All values in positions m+1 through myStuff.length-1 are
greater than or equal to n.
(d) The smallest value is at position m.
(e) The largest value that is smaller than n is at position m.
See this page to understand a method syntax
http://www.tutorialspoint.com/java/java_methods.htm
int m = mystery(n); means this method going to return int value and you are assigning that value to a int variable m. So your final result is m. the loop will run from the array's end position to 0. loop will break down when array's current position value is less than your parameter n. on that point it will return the loop's current position. s o now m=current loop position. If all the values of the loop is greater than n it will return -1 because if condition always fails.
Place the sample code into a Java IDE such as Eclipse, Netbeans or IntelliJ and then step through the code in the debugger in one of those environments.
Given that you are starting out I will give you the remainder of the code that you need to make this compile and run
public class MysteriousAlright {
private int[] myStuff;
public int mystery(int num)
{
for (int k = myStuff.length - 1; k >= 0; k--) {
if (myStuff[k] < num) {
return k;
}
}
return -1;
}
public static void main(String[] args) {
MysteriousAlright ma = new MysteriousAlright();
ma.setMyStuff(new int[] {4,5,6,7});
int m = ma.mystery(5);
System.out.println("I called ma.mystery(5) and now m is set to " + m);
m = ma.mystery(3);
System.out.println("I called ma.mystery(3) and now m is set to " + m);
m = ma.mystery(12);
System.out.println("I called ma.mystery(12) and now m is set to " + m);
}
public void setMyStuff(int[] myStuff) {
this.myStuff = myStuff;
}
}
You then need to learn how to use the debugger and/or write simple Unit Tests.
Stepping through the code a line at a time and watching the values of the variables change will help you in this learning context.
Here are two strategies that you can use to breakdown nonsense code like that which you have sadly encountered in this "educational" context.
Black Box examination Strategy
Temporarily ignore the logic in the mystery function, we treat the function as a black box that we cannot see into.
Look at what data gets passed in, what data is returned.
So for the member function called mystery we have
What goes in? : int num
What gets returned : an int, so a whole number.
There are two places where data is returned.
Sometimes it returns k
Sometimes it returns -1
Now we move on.
White Box examination Strategy
As the code is poorly written, a black box examination is insufficient to interpret its purpose.
A white box reading takes examines the member function's internal logic (In this case, pretty much the for loop)
The for loop visits every element in the array called myStuff, starting at the end of the array
k is the number that tracks the position of the visited element of the array. (Note we count down from the end of the array to 0)
If the number stored at the visited element is less than num (which is passed in) then return the position of that element..
If none of elements of the array are less than num then return -1
So mystery reports on the first position of the element in the array (starting from the end of the array) where num is bigger than that element.
do you understand what a method is ?
this is pretty basic, the method mystery receives an int as a parameter and returns an int when you call it.
meaning, the variable m will be assigned the value that returns from the method mystery after you call it with n which is an int of some value.
"The part where I got stuck is trying to logically understand how a int m = mystery(n); How can a number equal a method?"
A method may or may not return a value. One that doesn't return a value has a return type of void. A method can return a primitive value (like in your case int) or an object of any class. The name of the return type can be any of the eight primitive types defined in Java, the name of any class, or an interface.
If a method doesn't return a value, you can't assign the result of that method to a variable.
If a method returns a value, the calling method may or may not bother to store the returned value from a method in a variable.

Java post-increment (++) not behaving as expected when passed as a parameter

I came across the following issue:
private void doStuff(int i) {
if(i>10) {
return;
}
doStuff(i++);
}
public void publicMethod() {
doStuff(i);
}
I would expect this to run doStuff 10 times and then return.
However i++ does not get executed before the doStuff is called again with 0.
Result is an infinite loop. I know how to fix it but I am wondering if this behaviour is correct or a bug.
Now I would expect this to run doStuff 10 times and then return, however i++ does not get execute before the doStuff is called again with 0.
Yes, the result of the post-increment operator is the original value... and then inside the next call to the method you've a new i. So in other words, this call:
doStuff(i++);
is equivalent to:
int original = i;
i = original + 1;
doStuff(original);
From JLS section 15.14.2:
The value of the postfix increment expression is the value of the variable before the new value is stored.
Given that you don't use i again afterwards (and thus any side-effect on it is pointless), why not just simplify your life?
doStuff(i + 1);
(As with all parameters in Java, you're seeing pass-by-value - changing the value of i in the method does not change the value of the caller's argument.)
It behaves as expected it should, you probably want to replace i++ with ++i.
Check the oracle documentation on how to use the prefix/postfix unary increment operator:
class PrePostDemo {
public static void main(String[] args){
int i = 3;
i++;
// prints 4
System.out.println(i);
++i;
// prints 5
System.out.println(i);
// prints 6
System.out.println(++i);
// prints 6
System.out.println(i++);
// prints 7
System.out.println(i);
}
}
(excerpt from the linked page)
The ++ operator works just as expected. it first returns the value of the variable, and then increases the variable, hence you always pass 0.
This:
doStuff(i++);
is like:
int x = i;
i += 1;
doStuff(x);
i++ means that: "use value of i and then increment it". It will always be zero when passed down. It is a value type, not a reference type. If that would be an object, that would be no problem because it would be handled as reference.

Categories