请帮我修改一个模拟简单计算器的Java程序代码。
它读取两个整数和一个字符。如果字符是+,则打印总和;如果是 - ,则会打印出差异;如果是*,则打印产品;如果是/,则打印出商;如果是%,则打印剩余部分。
import java.util.Scanner;
class calc {
private int a,b,and;
private char c;
public static void main (String args[])
{
System.out.println ("Enter the first Integer");
Scanner scan = new Scanner (System.in);
a=scan.nextInt();
System.out.println("Enter the second Integer");
b=scan.nextInt();
System.out.println("Enter the operation sign");
c=scan.nextChar();
if (c=='+')
and=a+b;
else if (c=='-')
and=a-b;
else if (c=='*')
and=a*b;
else if (c=='/')
and=a/b;
else if (c=='%')
and=a%b;
else
{
System.out.println("Wrong operation");
exit(0);
}
System.out.println("The result is "+ ans);
}
}
答案 0 :(得分:1)
更改
c=scna.nextChar();
到
c=scan.nextChar();
同时更改
exit(0)
到
System.exit(0)
b=scan.newxInt();
至b=scan.nextInt();
将所有Out
更改为out
答案 1 :(得分:1)
一些事情:
newxInt();
使用nextInt(); api of Scanner
import static java.lang.System.exit;
,这样您就可以使用exit(0);
而不会出现编译器的任何问题。编辑:仅用于OP(确保为变量赋予有意义的名称) -
import static java.lang.System.exit;
import java.util.Scanner;
public class calc {
public static void main(String args[]) {
int a, b, ans = 0;
char c;
System.out.println("Enter the first Integer");
Scanner scan = new Scanner(System.in);
a = scan.nextInt();
scan.nextLine();
System.out.println("Enter the second Integer");
b = scan.nextInt();
scan.nextLine();
System.out.println("Enter the operation sign");
c = scan.nextLine().charAt(0);
if (c == '+')
ans = a + b;
else if (c == '-')
ans = a - b;
else if (c == '*')
ans = a * b;
else if (c == '/')
ans = a / b;
else if (c == '%')
ans = a % b;
else {
System.out.println("Wrong operation");
exit(0);
}
System.out.println("The result is " + ans);
}
}
Output:
Enter the first Integer
10
Enter the second Integer
20
Enter the operation sign
+
The result is 30