
正文
java递归四则运算代码 java递归例子
提示:扫一扫查出行【扫一扫了解最新限行尾号】
复制提示
求助写一个四则运算的JAVA程序,要求:有括号,私有,有计算过程(比如:1+2+3,输出结果为 1+2+3=3+3=6)
package test;
import java.util.*;
public class demo2 {
private static int intercePosition = 0; // 记录单个运算数据的长度
private static int[] intercePositionIndex = null; // 记录“(”的下标
private static int[] intercePositionEnd = null; // 记录“)”的下标
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
do {
System.out.println("请输入你要计算的字符串(注意:只能输入数字和加,减,乘除符号;输入完毕后,请直接回车):");
String numberString = input.next().trim();
// 判断输入的运算字符串是否符合规定
if (ispassString(numberString) == false) {
System.out.println("您输入的计算字符串有误,请正确输入!");
} else {
// 计算结果返回
System.out.println(interceResult(numberString));
}
} while (true);
}
// 判断是否有带括号的运算字符串存在
private static String interceResult(String str) {
String result = str;
char[] numberString = str.toCharArray(); // 1+2+(1*2+1-1*2+5)+2+(1+5+9+10-11)+1*5/2+3
// 1+8-9+(1*8/2-5+(1+2+8))+4/5*8/3*2
int IndexStart = 0; // 记录“(”的实际数量
int EndStart = 0; // 记录“)”的实际数量
for (int i = 0; i numberString.length; i++) {
if ('(' == numberString[i]) {
// 记录最后一个正括号的位置
IndexStart = i;
}
if (')' == numberString[i]) {
// 记录反括号的最初始下标的位置
EndStart = i;
// 截取最里面一个括号里的运算字符串
result = result.substring(IndexStart + 1, EndStart);
// 截取括号的运算字符串进行运算,生成新的运算字符串
result = str.substring(0, IndexStart)
+ interceptOperation(result, '*', '/')
+ str.substring(EndStart + 1, str.length());
// 回调执行,其它小括号的运算字符串
return interceResult(result);
}
if (i == numberString.length - 1)
if (EndStart == 0)
break;
}
// 不存在括号了,再进行混合运算
result = interceptOperation(str, '*', '/');
return result;
}
// 不带括号的四则运算
private static String interceptOperation(String operationNumber, char a,
char b) {
String mess = operationNumber;
char[] stringOperation = mess.toCharArray();
// 循环遍历运算字符串,并做相应的运算
for (int i = 0; i stringOperation.length; i++) {
// 判断运算符所在的索引
if (stringOperation[i] == a || stringOperation[i] == b) {
if (i != 0) {
// 运算符前的第一个数
double num1 = interceptNumIndex(mess.substring(0, i));
// 记录第一个数据的长度
int frontPosition = intercePosition;
// 运算符前的第二个数
double num2 = interceptNumEnd(mess.substring(i + 1,
stringOperation.length));
// 记录第二个数据的长度
int backPosition = intercePosition;
// 算完乘除,将结果替换到原来运算的位置,得到新的运算字符串
String IndexMess = mess.substring(0, i - frontPosition + 1);
String IndexResult = "";
// 判断是否运算到最后的结果了
if (IndexMess.indexOf('+') == -1
IndexMess.indexOf('*') == -1
IndexMess.indexOf('/') == -1
IndexMess.lastIndexOf('-') == -1)
IndexMess = "";
if (IndexMess != "")
IndexResult = IndexMess.lastIndexOf('-') == IndexMess
.length() - 1 ? IndexMess.substring(0, i
- frontPosition) : IndexMess;
// 组装新的运算字符串
mess = IndexResult// mess.substring(0,i-frontPosition+1)
+ reslutString("" + stringOperation[i], num1, num2)
+ mess.substring(i + backPosition + 1);
// 0.111/1212/2/2/2/2/2/2/2
if (mess.lastIndexOf('-') == 0 mess.indexOf('+') == -1
mess.indexOf('*') == -1
mess.indexOf('/') == -1) {
break;
}
// 回调,继续运算
return interceptOperation(mess, a, b);// 1+7-5+89/3+4-6*8/2+4-6
} else
continue;
}
if (i == stringOperation.length - 1) {
// 递归出口,判断是否还有运算字符串在
if (mess.indexOf('+') != -1 || mess.indexOf('-') != -1)
return interceptOperation(mess, '+', '-');
break;
}
}
return mess;
}
// 截取第二个数
private static double interceptNumEnd(String str) {
double a = 0;
int InrerceIndex = 0;
char[] stringOperation = str.toCharArray();
boolean ispas = false; // 记录是否为负数
for (int i = 0; i stringOperation.length; i++) {
switch (stringOperation[i]) {
case '*':
case '/':
case '+':
case '-':
InrerceIndex = i;
if (i != 0) // 判断该数是否为负数
ispas = true;
break;
default:
break;
}
if (ispas)
break;
}
// 判断此数据是否在运算字符串的最后一位
if (InrerceIndex == 0) {
a = Double.parseDouble(str);
intercePosition = str.length();
if (ispas)
intercePosition++;
} else {
a = Double.parseDouble(str.substring(0, InrerceIndex));
// 记录数据的真实长度
intercePosition = str.substring(0, InrerceIndex).length();
}
return a;
}
// 截取第一个数
private static double interceptNumIndex(String str) {
double a = 0; // 记录数据
int InrerceIndex = 0; // 记录运算符的位置
boolean temp = false; // 记录数据前运算符的状态
char[] stringOperation = str.toCharArray();
for (int i = stringOperation.length - 1; i = 0; i--) {
switch (stringOperation[i]) {
case '*':
case '/':
case '+':
case '-':
InrerceIndex = i;
temp = true;
break;
default:
break;
}
if (temp)
break;
}
// 判断此数据是否在运算字符串的第一位
if (InrerceIndex == 0) {
a = Double.parseDouble(str);
intercePosition = str.length();
// if(temp)
// intercePosition++;
} else {
a = Double.parseDouble(str.substring(InrerceIndex, str.length()));
// 记录数据的真实长度
intercePosition = str.substring(InrerceIndex, str.length())
.length();
}
return a;
}
// 计算结果
private static double reslutString(String operation, double num1,
double num2) {
double sumResult = 0;
if (operation.equals("*"))
sumResult = num1 * num2;
if (operation.equals("-"))
sumResult = num1 - num2;
if (operation.equals("/"))
sumResult = num1 / num2;
if (operation.equals("+"))
sumResult = num1 + num2;
return sumResult;
}
// 判断是否正确输入运算方式
private static boolean ispassString(String messString) {
boolean ispass = false;
boolean operationIspass = true; // 记录被除数的状态
int ai = 0; // 记录是否有运算符号的存在
char[] IsString = messString.toCharArray();
int num1 = 0;
int num2 = 0;
for (int i = 0; i IsString.length; i++) {
// 记录有几对小括号的存在
if ('(' == IsString[i])
num1++;
if (')' == IsString[i])
num2++;
// 判断除数是否为零
if ('/' == IsString[i] IsString[i + 1] == '0')
operationIspass = false;
// 判断是否输入了运算符合
if (IsString[i] == '+' || IsString[i] == '-' || IsString[i] == '*'
|| IsString[i] == '/')
ai++;
if (i == IsString.length - 1)
if (ai == 0)
num2++;
}
if (operationIspass)
if (num1 == num2)
ispass = true;
return ispass;
}
}
相关问答
Q1: 编写一个实现四则运算的JAVA程序
import java.text.DecimalFormat;
import java.util.Scanner;
public class Zhidao {
public static void main(String[] args) {
String condition = "";
Zhidao zhidao = new Zhidao();
do{
Scanner scanner = new Scanner(System.in);
try{
System.out.print("请输入第一个数:");
double x = scanner.nextDouble();
System.out.print("请输入第二个数:");
double y = scanner.nextDouble();
System.out.print("请输入运算符:");
String s = scanner.next();
char z = s.charAt(0);
zhidao.yunsuan(x, y, z);
}catch(Exception e){
System.out.println("请输入正确的数据!");
}
System.out.print("是否继续?continue:继续,任意字符:结束");
condition = scanner.next();
}while("continue".equals(condition));
}
public static void yunsuan(double x,double y,Character z){
DecimalFormat r=new DecimalFormat();
r.applyPattern("#0.00");
if(z.equals('+')){
System.out.println(x+"+"+y+"=" + r.format((x+y)));
} else if(z.equals('-')){
System.out.println(x+"-"+y+"=" + r.format((x-y)));
} else if(z.equals('*')){
System.out.println(x+"*"+y+"=" + r.format((x*y)));
} else if(z.equals('/')){
if(y==0){
System.out.println("被除数不能为0");
} else{
System.out.println(x+"/"+y+"=" + r.format((x/y)));
}
}else{
System.out.println("无法识别改运算符");
}
}
}
Q2: JAVA编程:四则运算(接收用户输入的2个操作数,和运算符),计算之后,输出结果:
import java.util.Scanner;
public class 四则运算 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("请输入第一个数字:");
int a = sc.nextInt();
System.out.print("请输入字符:");
String str = sc.next();
char ch = str.charAt(0);
System.out.print("请输入第二个数字:");
int b = sc.nextInt();
switch(ch)
{
case '+':
System.out.println(a+"+"+ b + "="+(a+b));
break;
case '-':
System.out.println(a+"-"+ b+ "="+(a-b));
break;
case '*':
System.out.println(a+"*"+ b+ "="+(a*b));
break;
case '/':
if(b==0){
System.out.println("被除数为零,运算无意义!");
break;
}
else {
System.out.println(a+"/"+ b+ " = "+(a/b));
break;
}
default:
System.out.println("运算符是无意义字符!");
break;
}
}
}
Q3: 如何用Java编写四则运算程序?
(首先建个类java递归四则运算代码,把这些复制粘贴进去)
import java.awt.*;
import javax.swing.*;
public class F {
JFrame frame = new JFrame("计算机");
JPanel pl = new JPanel();
JPanel p2 = new JPanel();
static JTextField show = new JTextField();
static JButton b0 = new JButton("0");
static JButton b1 = new JButton("1");
static JButton b2 = new JButton("2");
static JButton b3 = new JButton("3");
static JButton b4 = new JButton("4");
static JButton b5 = new JButton("5");
static JButton b6 = new JButton("6");
static JButton b7 = new JButton("7");
static JButton b8 = new JButton("8");
static JButton b9 = new JButton("9");
JButton bjia = new JButton("+");
JButton bjian = new JButton("-");
JButton bcheng = new JButton("*");
JButton bchu = new JButton("/");
JButton bdian = new JButton(".");
JButton bdeng = new JButton("=");
JButton bqingchu = new JButton("清除");
public void y() {
pl.setLayout(new GridLayout(1, 1));
pl.add(show);
}
public void p() {
b1.addActionListener(new U());
b2.addActionListener(new U());
b3.addActionListener(new U());
b4.addActionListener(new U());
b5.addActionListener(new U());
b6.addActionListener(new U());
b7.addActionListener(new U());
b8.addActionListener(new U());
b9.addActionListener(new U());
b0.addActionListener(new U());
bjia.addActionListener(new Fu());
bjian.addActionListener(new Fu());
bcheng.addActionListener(new Fu());
bchu.addActionListener(new Fu());
bdeng.addActionListener(new Deng());
bqingchu.addActionListener(new Qing());
p2.setLayout(new GridLayout(6, 3));
p2.add(b1);
p2.add(b2);
p2.add(b3);
p2.add(b4);
p2.add(b5);
p2.add(b6);
p2.add(b7);
p2.add(b8);
p2.add(b9);
p2.add(b0);
p2.add(bjia);
p2.add(bjian);
p2.add(bcheng);
p2.add(bchu);
p2.add(bdian);
p2.add(bqingchu);
p2.add(bdeng);
}
public void o() {
frame.setLayout(new BorderLayout());
frame.add(pl, BorderLayout.NORTH);
frame.add(p2, BorderLayout.CENTER);
frame.setSize(400, 300);
frame.setVisible(true);
}
public static void main(String[] args) {
F f = new F();
f.y();
f.p();
f.o();
}
}
(再新建个类 把这些也复制粘贴进去)
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class U implements ActionListener {
public static String str = "";
public static String a = "";
public static String b = "";
public static String k = "";
public void actionPerformed(ActionEvent e) {
String w = e.getActionCommand();//字
if (k.equals("")) {
a += w;
F.show.setText(a);
} else {
b += w;
F.show.setText(b);
}
}
}
(再新建一个java递归四则运算代码,把下面java递归四则运算代码的复制粘贴)
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class Deng implements ActionListener {
public void actionPerformed(ActionEvent e) {
int a = Integer.parseInt(U.a);
int b = Integer.parseInt(U.b);
int c = 0;
if (U.k.equals("+")) {
c = a + b;
} else
if (U.k.equals("-")) {
c = a - b;
} else
if (U.k.equals("*")) {
c = a * b;
} else
if (U.k.equals("/")) {
c = a / b;
} else {
}
String d = String.valueOf(c);
F.show.setText(d);
U.a = d;
U.b = "";
U.k = "";
}
}
(在建一个 复制粘贴)
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class Fu implements ActionListener {
public void actionPerformed(ActionEvent e) {
String a = e.getActionCommand();//字
U.k = a;
}
}
(在建一个)
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class Qing implements ActionListener {
public void actionPerformed(ActionEvent e) {
U.a = "";
U.b = "";
U.k = "";
F.show.setText("");
}
}
Q4: java用递归算法求 1-2+3-4+5-6......+
思路:先用递归求出一个数的阶乘,接着for循环累加求和。参考代码:pre t="code" l="cpp"#includestdio.h
int fun(int n){
if(n==1) return 1;//递归结束条件
return n*fun(n-1);//递归式
}
int main()
{
int sum=0,i;
for(i=1;i=6;i++)//for循环累加求和
sum+=fun(i);
printf("%d\n",sum);
return 0;
}
/*
运行结果:
873
*/
java递归四则运算代码的介绍就聊到这里吧,感谢你花时间阅读本站内容,更多关于java递归例子、java递归四则运算代码的信息别忘了在本站进行查找喔。







