java加减乘除运算代码

Certainly! Below is an example Java code that performs basic addition, subtraction, multiplication, and division operations:

java
public class BasicMathOperations { public static void main(String[] args) { // Addition int num1 = 10; int num2 = 5; int sum = num1 + num2; System.out.println("Addition: " + sum); // Subtraction int difference = num1 - num2; System.out.println("Subtraction: " + difference); // Multiplication int product = num1 * num2; System.out.println("Multiplication: " + product); // Division (Ensure num2 is not zero to avoid ArithmeticException) if (num2 != 0) { double quotient = (double) num1 / num2; System.out.println("Division: " + quotient); } else { System.out.println("Cannot divide by zero."); } } }

This code defines a class called BasicMathOperations with a main method. It performs addition, subtraction, multiplication, and division on two integer numbers (num1 and num2). Note that division is handled carefully to avoid division by zero.

Feel free to modify the numbers or use user input for more dynamic calculations.

Certainly! If you want to allow user input for the numbers, you can use the Scanner class. Here's an extended version of the code:

java
import java.util.Scanner; public class BasicMathOperations { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); // Get user input for the first number System.out.print("Enter the first number: "); int num1 = scanner.nextInt(); // Get user input for the second number System.out.print("Enter the second number: "); int num2 = scanner.nextInt(); // Addition int sum = num1 + num2; System.out.println("Addition: " + sum); // Subtraction int difference = num1 - num2; System.out.println("Subtraction: " + difference); // Multiplication int product = num1 * num2; System.out.println("Multiplication: " + product); // Division (Ensure num2 is not zero to avoid ArithmeticException) if (num2 != 0) { double quotient = (double) num1 / num2; System.out.println("Division: " + quotient); } else { System.out.println("Cannot divide by zero."); } // Close the scanner to prevent resource leaks scanner.close(); } }

This version uses the Scanner class to get user input for the two numbers. Make sure to close the Scanner at the end to prevent resource leaks. Now, users can input their own numbers when running the program.