//JAVA编程:四则运算(接收用户输入的2个 *** 作数,和运算符),计算之后,输出结果~~~~\x0d\x0aimportjava.util.Scanner\x0d\x0apublicclass四则运算{\x0d\x0apublicstaticvoidmain(String[]args){\x0d\x0aScannersc=newScanner(System.in)\x0d\x0aSystem.out.print("
请输入第一个数字:")\x0d\x0ainta=sc.nextInt()\x0d\x0aSystem.out.print("请输入运算符号:")\x0d\x0aStringstr=sc.next()\x0d\x0acharch=str.charAt(0)\x0d\x0aSystem.out.print("请输入第二个数字:")\x0d\x0aintb=sc.nextInt()\x0d\x0aswitch(ch)\x0d\x0a{\x0d\x0acase'+':\x0d\x0aSystem.out.println(a+"+"+b+"="+(a+b))\x0d\x0abreak\x0d\x0acase'-':\x0d\x0aSystem.out.println(a+"-"+b+"="+(a-b))\x0d\x0abreak\x0d\x0acase'*':\x0d\x0aSystem.out.println(a+"*"+b+"="+(a*b))\x0d\x0abreak\x0d\x0acase'/':\x0d\x0aif(b==0){\x0d\x0aSystem.out.println("
被除数为零,运算
无意义!")\x0d\x0abreak\x0d\x0a}\x0d\x0aelse{\x0d\x0aSystem.out.println(a+"/"+b+"="+(a/b))\x0d\x0abreak\x0d\x0a}\x0d\x0adefault:\x0d\x0aSystem.out.println("运算符是无意义字符!")\x0d\x0abreak\x0d\x0a}\x0d\x0a}\x0d\x0a}\x0d\x0a\x0d\x0a望采纳~~~~~~~~import java.util.Scanner
public class HybridOperation {
public static void main(String[] args) {
Scanner input = new Scanner(System.in)
System.out.println("输入一个表达式:")
String s = input.nextLine().trim()
int n = s.length()
int sum = 0
int p = -1
char a = '+'
for (int i = 1i <ni++) {
char ch = s.charAt(i)
if (ch == '+' || ch == '-') {
if (a == '+') {
sum += Integer.parseInt(s.substring(p + 1, i))
a = ch
p = i
} else if (a == '-') {
sum -= Integer.parseInt(s.substring(p + 1, i))
a = ch
p = i
}
}
}
if (a == '+') {
sum += Integer.parseInt(s.substring(p + 1))
}
if (a == '-') {
sum -= Integer.parseInt(s.substring(p + 1))
}
System.out.println(s+" = "+sum)
}
}
可以实现任意次数的加减,
如:1+2+3-2
评论列表(0条)