帮忙修改一段JAVA程序!
发布网友
发布时间:2024-10-23 20:48
我来回答
共2个回答
热心网友
时间:2024-11-02 16:07
刚漏下一个break.
import java.io.*;
public class cal {
public static void main(String[] args) throws IOException {
System.out.println("请输入第一个操作数!");
BufferedReader buf1;
String str1;
buf1 = new BufferedReader(new InputStreamReader(System.in));
str1 = buf1.readLine();
System.out.println("请输入运算符!");
BufferedReader buf2;
String str2;
buf2 = new BufferedReader(new InputStreamReader(System.in));
str2 = buf2.readLine();
char[] char2 = str2.toCharArray();
System.out.println("请输入第二个操作数!");
BufferedReader buf3;
String str3;
buf3 = new BufferedReader(new InputStreamReader(System.in));
str3 = buf3.readLine();
System.out.println(" 结果为: "+yunsuan(str1, char2[0], str3));
}
public static int yunsuan(String x, char y, String z) {
char b = y;
int a = Integer.parseInt(x);
int c = Integer.parseInt(z);
int result = 0 ;
switch (b) {
case '+':
result = a + c;
break;
case '-':
result = a - c;
break;
case '*':
result = a * c;
// sub=a*c;
// System.out.println("a+"*"+c+"="+sub");
break;
case '/':
result = a / c;
// sub=a/c;
// System.out.println("a+"/"+c+"="+sub");
break;
default:
System.out.println("输入非法!");
break;
}
return result;
}
}
输入内容要符合要求:
例如:
请输入第一个操作数!
1
请输入运算符!
+
请输入第二个操作数!
3
结果为: 4
不要多空格之类的。
热心网友
时间:2024-11-02 16:05
public class cal {
public static void main(String[] args) {
System.out.println("请输入第一个操作数!");
BufferedReader buf1 = null;
try {
String str1;
buf1 = new BufferedReader(new InputStreamReader(System.in));
str1 = buf1.readLine();
System.out.println("请输入运算符!");
//BufferedReader buf2;
String str2;
// buf2 = new BufferedReader(new InputStreamReader(System.in));
str2 = buf1.readLine();
java.lang.Character c = new Character(str2.charAt(0));
System.out.println("请输入第二个操作数!");
//BufferedReader buf3;
String str3;
// buf3 = new BufferedReader(new InputStreamReader(System.in));
str3 = buf1.readLine();
try {
int result = yunsuan(str1, c, str3);
System.out.println(str1 + " " + c + " " + str3 + " = " + result);
} catch (RuntimeException e) {
System.out.println(e.getMessage());
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
buf1.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public static int yunsuan(String x, char y, String z) {
char b = y;
int a =0;
int c =0;
try {
a= Integer.parseInt(x);
c= Integer.parseInt(z);
} catch (NumberFormatException e) {
throw new RuntimeException("输入非法!");
}
int result = 0;
switch (b) {
case '+':
result = a + c;
break;
case '-':
result = a - c;
break;
// sub=a-c;
// System.out.println("a+"-"+c+"="+sub");
case '*':
result = a * c;
break;
// sub=a*c;
// System.out.println("a+"*"+c+"="+sub");
case '/':
// sub=a/c;
// System.out.println("a+"/"+c+"="+sub");
result = a / c;
break;
}
return result;
}
}