Write a program that takes a single integer input from the user and stores it in a variable. Your program should increase the value of this variable by one four times, printing "number is now " followed by its value each time, then decrease it by one four times, again printing "number is now " and the value each time. You must use unary operators to increase/decrease the value of the variable to receive full credit for this assignment.

in java

1 answer

Certainly! Below is a Java program that fulfills your requirements. It takes a single integer input from the user, increments the value by one four times, and then decrements it by one four times, printing the value after each operation.

import java.util.Scanner;

public class IncrementDecrement {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        // Prompt user for input
        System.out.print("Enter an integer: ");
        int number = scanner.nextInt();

        // Increment the number by one four times
        for (int i = 0; i < 4; i++) {
            number++; // Increment using unary operator
            System.out.println("number is now " + number);
        }

        // Decrement the number by one four times
        for (int i = 0; i < 4; i++) {
            number--; // Decrement using unary operator
            System.out.println("number is now " + number);
        }

        // Close the scanner
        scanner.close();
    }
}

How the Program Works

  1. The program starts by importing the Scanner class to handle user input.
  2. It prompts the user to enter an integer and stores it in the variable number.
  3. The first for loop runs four times, using the ++ operator to increment number and print its value after each increment.
  4. The second for loop runs four times, using the -- operator to decrement number and print its value after each decrement.
  5. Finally, the scanner is closed to avoid resource leaks.

Usage

To use the program, simply compile and run it, then input an integer when prompted. The program will show you the incremented and decremented values in sequence.