用JAVA判断输入的公式
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了用JAVA判断输入的公式相关的知识,希望对你有一定的参考价值。
JAVA程序,要用GUI实现像计算器
1.建立2个stack,一个存储+,-,*,/,(,),另一个存储数字
2. 输入一个带数字的公式(整数),判断这个输入的公式是不是正确,3.在页首写上:欢迎来到线性的数据结构
例子:
输入:
(5+5) + 6*3 + 18
正确((6+5) + 6*3 + 18
少右括号(7+5) + 6*3 + 18))
少左括号
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.ArrayList;
import java.util.List;import javax.swing.JButton;
import javax.swing.JTextField;@SuppressWarnings("serial")
public class Calc extends Frame
public static final int WIN_HEIGHT = 321;
public static final int WIN_WIDTH = 228;
private JTextField calcText = new JTextField("0");
String[] inStr = new String[] "(", ")", "D", "+",
"7", "8", "9", "-",
"4", "5", "6", "*",
"1", "2", "3", "/",
"0", ".", "C", "=";
public void init()
this.setSize(WIN_WIDTH, WIN_HEIGHT);
this.setVisible(true);
this.addWindowListener(new WindowAdapter()
public void windowClosing(WindowEvent e)
System.exit(0);
);
this.setLayout(null);
this.setTitle("Calc");
calcText.setVisible(true);
calcText.setHorizontalAlignment(JTextField.RIGHT);
this.add(calcText);
calcText.setBounds(20, 40, 190, 25);
//创建btn
JButton btn;
for(int i = 1, j = 0; i <= inStr.length; i++)
btn = new JButton(inStr[i-1]);
this.add(btn);
btn.addMouseListener(new MyMouse());
btn.setBounds(20 + (45 + 3) * ((i-1) % 4), 70 + (43 + 2) * j, 45, 43);
if(i % 4 == 0)
j++;
class MyMouse extends MouseAdapter
public void mouseClicked(MouseEvent e)
JButton btn = (JButton)e.getSource();
String action = btn.getText();
if("C".equals(action))
calcText.setText("");
else if("D".equals(action))
String str = calcText.getText();
calcText.setText(str.substring(0, str.length() - 1));
else if("=".equals(action))
try
calcText.setText(separate(calcText.getText()) + "");
catch (Exception e1)
calcText.setText("式子错误");
else
calcText.setText(calcText.getText() + action);
public static void main(String[] args)
new Calc().init();
//拆除括号进行计算
public double separate(String str) throws Exception
double re = 0;
System.out.println(str);
//如果不存在括号,进行直接计算
if( ( !str.contains("(")) && (!str.contains(")") ) )
re = calculate(str);
else
//若有括号,继续进一步拆解括号计算
String oldStr = extract(str);
String newStr = calculate(extract(str)) + "";
re = separate(str.replace(oldStr, strValue(Double.parseDouble(newStr))));
return re;
private String strValue(Double d)
if(d % 1 == 0)
return ""+d.intValue();
return d.toString();
//拆解括号
public String extract(String str) throws Exception
String childStr = str.substring(str.indexOf('(') + 1, str.length());
if(!childStr.contains("("))
return str.substring(str.indexOf('(') , str.indexOf(')') + 1);
if(childStr.indexOf('(') - childStr.indexOf(')') > 0)
return str.substring(str.indexOf('(') , str.indexOf(')') + 1);
else
return extract(childStr);
//无括号表达式直接计算
public double calculate(String str)
double re = 0;
Formula f = new Formula(str);
if(f.hasAction())
re += calculate(f.toString());
else
re += Double.parseDouble(f.toString());
return re;
class Formula
private List<Character> strList = new ArrayList<Character>();
private List<Double> doubleList = new ArrayList<Double>();
private char action = '0';
private String sourceStr;
public Formula(String str)
str = str.trim().replace("(", ")").replace(")", " ").replace(" ", "") ;
sourceStr = str;
char[] chars = str.toCharArray();
String num = "";
for(char c : chars)
//非数字和.
if((c < 48 || c > 57) && c != 46)
strList.add(c);
setAction(c);
doubleList.add(Double.parseDouble(num));
num = "";
else
num += c;
if(!"".equals(num))
doubleList.add(Double.parseDouble(num));
public boolean hasAction()
return action != '0';
public void setAction(char c)
if(action == '0')
action = c;
return;
if((action == '/' || action == '*'))
return;
else if(c == '*' || c=='/')
action = c;
public String toString()
if(!hasAction())
return sourceStr;
int index = strList.indexOf(action);
double num1 = doubleList.get(index);
double num2 = doubleList.get(index+1);
switch(action)
case '+':
return sourceStr.replace(strValue(num1) + action + strValue(num2), strValue(num1+num2) + "");
case '-':
return sourceStr.replace(strValue(num1) + action + strValue(num2), strValue(num1-num2) + "");
case '*':
return sourceStr.replace(strValue(num1) + action + strValue(num2), strValue(num1*num2) + "");
case '/':
return sourceStr.replace(strValue(num1) + action + strValue(num2), strValue(num1/num2) + "");
case '0':
return sourceStr;
return sourceStr;
我也没有详细的测。你测试一下,如果式子是错误的会在文本框输出 式子错误。控制台会输出 计算 步骤。功能算是实现了,再有什么问题直接QQ叫我好了。
怎样用JAVA写判断一个年份是否闰年的程序?
/***
*/
/**
* @author qingsongwang
*
*/
import java.util.*;
public class B
public static boolean isRun(int year)
return (year % 4 != 0 )|| (year % 100 == 0 )&& (year % 400 != 0);
public static void main(String[] args)
Scanner input=new Scanner(System.in);
int year;
System.out.printf("你输入的年份是:%s", year=input.nextInt());
if(isRun(year))
System.out.print("(是闰年)");
else
System.out.print("(不是闰年)");
直接运行这个程序即可! 参考技术A public class LeapYear
public boolean isLeap(int year)
if ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0)
return true;
else
return false;
/**
* @param args
*/
public static void main(String[] args)
LeapYear l = new LeapYear();
for (int i = 0; i < 2000; i++)
if (l.isLeap(i))
System.out.println(i);
参考技术B import java.util.*;
public class year
public static void main(String[]args)
Scanner input= new Scanner(System.in);
for(int i=0;;i++)
System.out.println("请输入年份:");
int nian = input.nextInt();
if(nian % 4 != 0 || nian % 100 == 0 && nian % 400 != 0)
System.out.println(nian+"是平年");
else
System.out.println(nian+"是闰年");
参考技术C 怎样判断一个年份是不是闰年 参考技术D import java.util.GregorianCalendar;
public class Leap
public static void main(String[] args)
GregorianCalendar cal = new GregorianCalendar();
int year = 2008;
System.out.println(year + (cal.isLeapYear(2008)?"是闰年":"不是闰年"));
以上是关于用JAVA判断输入的公式的主要内容,如果未能解决你的问题,请参考以下文章