1

Basically the goal of the program is to have the user input a number, increase is 3 times, then decrease it 3 times using unary operators. The issue is that when it's ran, the first "number is now ___" line ends up just showing the same number the user inputed rather than increasing it by one. New to Java, Don't really know why

import java.util.Scanner;

class U1_L4_Activity_One{
  public static void main(String[] args){
      
      int num;
      Scanner startNum = new Scanner(System.in);
      
      //Enter an int (num)
      System.out.println("Enter starting number(must be an integer)");
      num = startNum.nextInt();
      
      //Increases num 3 times
      System.out.println("number is now " + num++);
      System.out.println("number is now " + num++);
      System.out.println("number is now " + num++);
      //Decreases num 3 times, back to original number
      System.out.println("number is now " + num--);
      System.out.println("number is now " + num--);
      System.out.println("number is now " + num--);
  }
}
  • 1
    Does this answer your question? [Is there a difference between x++ and ++x in java?](https://stackoverflow.com/questions/1094872/is-there-a-difference-between-x-and-x-in-java) –  Aug 25 '20 at 05:29

2 Answers2

1

The ++ unary operator can be used as a post-increment or pre-increment operator. In this case, since you have added the ++ after the num variable, it is performing a post-increment operation. This means that the num variable value is displayed first and then will be incremented by 1. This is the reason the number is printed first and then incremented causing the same number to display again.

To fix this you can make use of the pre-increment operation.

  System.out.println("number is now " + ++num); // <-- the num is incremented first and then displayed.
  System.out.println("number is now " + ++num);
  System.out.println("number is now " + ++num);
  //Decreases num 3 times, back to original number
  System.out.println("number is now " + --num); // <-- pre decrement operation
  System.out.println("number is now " + --num);
  System.out.println("number is now " + --num);
glegshot
  • 74
  • 7
0

It's because num++ increments its value in the "background" and then returns it. If you want to increment num and immediatly return the value, you should use ++num.

André Frings
  • 119
  • 1
  • 5
  • 15