Java Arithmetic Operator Question 2

Question

We would like to write an application that asks the user to enter two integers.

The get them from the user and print their sum, product, difference and quotient (division).

import java.util.Scanner;

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

        //your code here
    }
}



import java.util.Scanner;

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

        int difference = 0;
        int quotient = 0;

        System.out.print("Enter 2 integers separated by a space: ");
        int x = input.nextInt();
        int y = input.nextInt();

        // sum
        printSolution("Sum", x + y);

        // product
        printSolution("Product", x * y);

        // difference
        printSolution("Difference", Math.abs(x - y));

        if(x != 0 && y != 0)
            printSolution("Quotient", y % x);
        else
            printSolution("Quotient error: Cannot divide by zero", 0);
    }
    private static void printSolution(String message, int value){
        System.out.printf("%s = %d\n", message, value);
    }
}

Or you can do


package chapter2;

import java.util.Scanner;

public class Main {

  public static void main(String[] args) {
    /* w  w w .ja v  a 2  s  .c  o m*/
    // Declaring variables needed for exercise
    Scanner input = new Scanner(System.in);
    int x, y;
    int xsquare, ysquare;
    int sumsquare;
    int difsquare;
    
    // Prompting user for two integers
    System.out.print("Enter first integer: ");
    x = input.nextInt();
    System.out.println("Eter second integer: ");
    y = input.nextInt();
    
    // Performing calculations as described in exercise specification
    xsquare = x * x;
    ysquare = y * y;
    sumsquare = xsquare + ysquare;
    difsquare = xsquare - ysquare;
    
    // Displaying results to user
    System.out.printf("Square of x = %s, Square o y = %s.%nSum of squares = %s, Difference of squares = %s", 
        xsquare, ysquare, sumsquare, difsquare);
    
    input.close();
  }
}



PreviousNext

Related