把这个c++代码翻译成Java#include <iostream> using namespace std; int main() { char op; float num1, num2; cout << "Enter operator (+, -, , /): "; cin >> op; cout << "Enter two operands: "; cin >> num1 >> num2; switch(op) { case '+': cout << num1+num2; break; case '-': cout << num1-num2; break; case '': cout << num1*num2; break; case '/': if(num2 == 0) { cout << "Error: Division by zero"; } else { cout << num1/num2; } break; default: cout << "Error: Invalid operator"; break; } return 0; }
时间: 2024-05-04 09:21:57 浏览: 156
#include_iostream.h_
4星 · 用户满意度95%
以下是将该 C++ 代码翻译成 Java 的版本:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
char op;
float num1, num2;
System.out.print("Enter operator (+, -, *, /): ");
op = sc.next().charAt(0);
System.out.print("Enter two operands: ");
num1 = sc.nextFloat();
num2 = sc.nextFloat();
switch(op) {
case '+':
System.out.println(num1+num2);
break;
case '-':
System.out.println(num1-num2);
break;
case '*':
System.out.println(num1*num2);
break;
case '/':
if(num2 == 0) {
System.out.println("Error: Division by zero");
} else {
System.out.println(num1/num2);
}
break;
default:
System.out.println("Error: Invalid operator");
break;
}
}
}
阅读全文