Skip to content

Instantly share code, notes, and snippets.

@SeanTOSCD
Last active May 30, 2023 22:18
Show Gist options
  • Save SeanTOSCD/0e8193a4a71764f5d40c5da8cc1244ee to your computer and use it in GitHub Desktop.
Save SeanTOSCD/0e8193a4a71764f5d40c5da8cc1244ee to your computer and use it in GitHub Desktop.
Basic Arithmetic Expressions in Java
/**
* Basic Expressions
*
* @author Sean Davis
*/
package edu.umsl;
import java.util.Scanner;
/**
* Given values for 'x' and 'y', do basic arithmetic and output the results
*/
public class JavaExpressionsHW {
// Assign value to x
int x = 10;
// Assign value to y
int y = 20;
// Declare z
int z;
public static void main(String[] args) {
// A new instance of the class
JavaExpressionsHW expressions = new JavaExpressionsHW();
// Call program heading method
expressions.programHeading();
// Run all the calculations separately using x and y fields
expressions.calcSum();
expressions.calcDifference();
expressions.calcProduct();
expressions.calcQuotient();
expressions.calcRemainder();
// Now take user input for x and y and run the calculations again
expressions.userInput();
}
// Output the program heading
public void programHeading() {
System.out.println("Where 'x' equals " + x + " and 'y' equals " + y + ", the following statements are true:");
}
public void userInput() {
System.out.println("\nNow let's use custom values for 'x' and 'y'.\n");
Scanner input = new Scanner(System.in);
System.out.print("Enter a value for x: ");
x = input.nextInt();
System.out.print("Enter a value for y: ");
y = input.nextInt();
System.out.println("\nWhere 'x' equals " + x + " and 'y' equals " + y + ", the updated statements are true:");
calcSum();
calcDifference();
calcProduct();
calcQuotient();
calcRemainder();
}
// Output the sum of x and y
public void calcSum() {
z = x + y;
System.out.println("- The sum of " + x + " and " + y + " is " + z + ".");
}
// Output the difference between x and y
public void calcDifference() {
z = x - y;
System.out.println("- The difference between " + x + " and " + y + " is " + z + ".");
}
// Output the product of x and y
public void calcProduct() {
z = x * y;
System.out.println("- The product of " + x + " and " + y + " is " + z + ".");
}
// Output the quotient of x and y
public void calcQuotient() {
z = x / y;
System.out.println("- The quotient of " + x + " and " + y + " is " + z + ".");
}
// Output the remainder of x and y
public void calcRemainder() {
z = x % y;
System.out.println("- The remainder of " + x + " and " + y + " is " + z + ".");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment