我才看过不到1个星期的入门语法
算是作业吧 我有计算器流程图 以前用VB做过
现在要求用java写 一点思路都没有
如何开始 应该先考虑什么 怎么实现之类的 求大侠给个提示 或者举例子也好
我还是想自己做出来的 网上刚才是搜索到许多例子 但还不太明白
谢谢了
算是作业吧 我有计算器流程图 以前用VB做过
现在要求用java写 一点思路都没有
如何开始 应该先考虑什么 怎么实现之类的 求大侠给个提示 或者举例子也好
我还是想自己做出来的 网上刚才是搜索到许多例子 但还不太明白
谢谢了
import java.awt.*;
import java.awt.event.*;
public class Calculator extends JFrame implements ActionListener
{
private boolean dotExist, operated, equaled; // 帮助运算的布尔变量
private double storedNumber; // 目前的结果
private char lastOperator; // 表示上一运算符
private JTextField operation; // 结果栏
private JButton dot, plus, minus, multi, div, sqrt, equal, changePN, clear; // 运算符
private JButton[] numbers; // 数字
// 构造者
public Calculator()
{
setTitle("Calculator");
// 初始化变量
dotExist = false; // 表示当前的数是否有小数点
operated = false; // 表示任意运算符是否被按下
equaled = false; // 表示等号是否被按下
storedNumber = 0;
lastOperator = '?';
// 初始化窗口变量
operation = new JTextField("0");
operation.setEditable(false);
numbers = new JButton[10];
for (int i = 0; i < 10; i++)
numbers[i] = new JButton("" + i);
dot = new JButton(".");
plus = new JButton("+");
minus = new JButton("-");
multi = new JButton("*");
div = new JButton("/");
sqrt = new JButton("√");
equal = new JButton("=");
changePN = new JButton("±");
clear = new JButton("AC");
// 将窗口物体放入窗口
GridBagLayout layout = new GridBagLayout();
getContentPane().setLayout(layout);
addComponent(layout, operation, 0, 0, 4, 1);
addComponent(layout, numbers[1], 1, 0, 1, 1);
addComponent(layout, numbers[2], 1, 1, 1, 1);
addComponent(layout, numbers[3], 1, 2, 1, 1);
addComponent(layout, numbers[4], 2, 0, 1, 1);
addComponent(layout, numbers[5], 2, 1, 1, 1);
addComponent(layout, numbers[6], 2, 2, 1, 1);
addComponent(layout, numbers[7], 3, 0, 1, 1);
addComponent(layout, numbers[8], 3, 1, 1, 1);
addComponent(layout, numbers[9], 3, 2, 1, 1);
addComponent(layout, dot, 4, 0, 1, 1);
addComponent(layout, numbers[0], 4, 1, 1, 1);
addComponent(layout, sqrt, 4, 2, 1, 1);
addComponent(layout, plus, 1, 3, 1, 1);
addComponent(layout, minus, 2, 3, 1, 1);
addComponent(layout, multi, 3, 3, 1, 1);
addComponent(layout, div, 4, 3, 1, 1);
addComponent(layout, equal, 5, 0, 2, 1);
addComponent(layout, changePN, 5, 2, 1, 1);
addComponent(layout, clear, 5, 3, 1, 1);
}
// 对按钮进行反应的方法
public void actionPerformed(ActionEvent e)
{
JButton btn = (JButton)e.getSource();
if (btn == clear)
{
operation.setText("0");
dotExist = false;
storedNumber = 0;
lastOperator = '?';
}
else if (btn == equal)
{
operate('=');
equaled = true;
}
else if (btn == plus)
{
operate('+');
equaled = false;
}
else if (btn == minus)
{
operate('-');
equaled = false;
}
else if (btn == multi)
{
operate('*');
equaled = false;
}
else if (btn == div)
{
operate('/');
equaled = false;
}
else if (btn == changePN)
{
operate('p');
operate('=');
equaled = true;
}
else if (btn == sqrt)
{
operate('s');
operate('=');
equaled = true;
}
else
{
if (equaled)
storedNumber = 0;
for (int i = 0; i < 10; i++)
if (btn == numbers[i])
{
if (operation.getText().equals("0"))
operation.setText("" + i);
else if(! operated)
operation.setText(operation.getText() + i);
else
{
operation.setText("" + i);
operated = false;
}
}
if (btn == dot && ! dotExist)
{
operation.setText(operation.getText() + ".");
dotExist = true;
}
}
}
// 进行运算的方法
private void operate(char operator)
{
double currentNumber = Double.valueOf(operation.getText()).doubleValue();
if (lastOperator == '?')
storedNumber = currentNumber;
else if (lastOperator == '+')
storedNumber += currentNumber;
else if (lastOperator == '-')
storedNumber -= currentNumber;
else if (lastOperator == '*')
storedNumber *= currentNumber;
else if (lastOperator == '/')
storedNumber /= currentNumber;
else if (lastOperator == 'p')
storedNumber *= -1;
else if (lastOperator == 's')
storedNumber = Math.sqrt(currentNumber);
else if (lastOperator == '=' && equaled)
storedNumber = currentNumber;
operation.setText("" + storedNumber);
operated = true;
lastOperator = operator;
}
// 快捷使用GridBagLayout的方法
private void addComponent(GridBagLayout layout, Component component, int row, int col, int width, int height)
{
GridBagConstraints constraints = new GridBagConstraints();
constraints.fill = GridBagConstraints.BOTH;
constraints.insets = new Insets(10, 2, 10, 2);
constraints.weightx = 100;
constraints.weighty = 100;
constraints.gridx = col;
constraints.gridy = row;
constraints.gridwidth = width;
constraints.gridheight = height;
layout.setConstraints(component, constraints);
if (component instanceof JButton)
((JButton)component).addActionListener(this);
getContentPane().add(component);
}
// 主方法初始化并显示窗口
public static void main(String[] args)
{
Calculator calc = new Calculator();
calc.setSize(290, 400);
calc.setVisible(true);
}
}
public class Calculator implements ActionListener{
JTextField jtf=new JTextField(20);
private boolean append =false;
private String s1="0";
private String operator="+";
public Calculator(){
JFrame jf=new JFrame("Counter");
jf.add(jtf,BorderLayout.NORTH);
JPanel jp=new JPanel(new GridLayout(5,4));
jf.add(jp,BorderLayout.CENTER);
String[] ss={"BACK","CE","C","+",
"7","8","9","-",
"4","5","6","*",
"1","2","3","/",
"0","+/-",".","="
};
JButton[] jb=new JButton[20];
for(int i=0;i<jb.length;i++){
jb[i]=new JButton(ss[i]);
jb[i].addActionListener(this);
jp.add(jb[i]);
}
/*
* for(int i=0;i<jb.length;i++){
* JButton jb=new JButton(ss[i]);
* jp.add(jb);
* }
*/
jtf.setEditable(false);
jf.setResizable(false);
jf.setSize(400,300);
jf.setLocation(400,300);
jf.setVisible(true);
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public void actionPerformed(ActionEvent e) {
String comm=e.getActionCommand();
/*if(comm.matches("^\\d+$")){
jtf.setText(comm);
}*/
if("0123456789".indexOf(comm)!=-1){
if(append){
String temp=jtf.getText();
jtf.setText(comm);
}else{
jtf.setText(comm);
append=true;
}
}else if(".".equals(comm)){
String temp =jtf.getText();
if(temp.indexOf(".")==-1){
jtf.setText(temp+".");
append =true;
}
}else if("+-*/".indexOf(comm)!=-1){
s1=jtf.getText();
operator=comm;
append=false;
}else if("=".equals(comm)){
String s2=jtf.getText();
double d1=Double.parseDouble(s1);
double d2=Double.parseDouble(s2);
if("+".equals(operator)){
d1=d1+d2;
}else if("-".equals(operator)){
d1=d1-d2;
}else if("*".equals(operator)){
d1=d1*d2;
}else if("/".equals(operator)){
d1=d1/d2;
}
s1=d1+"";
if(s1.endsWith(".0")){
s1=s1.substring(0,s1.length());
}
jtf.setText(s1);
append=false;
}else if("+/-".equals(comm)){
String temp=jtf.getText();
if(temp.startsWith("-")){
jtf.setText(temp.substring(1));
}else{
jtf.setText("-"+temp);
}
}else if("C".equals(comm)||"CE".equals(comm)){
jtf.setText("0");
append =false;
}else if("BACK".equals(comm)){
String temp=jtf.getText();
if(temp.length()>0){
jtf.setText(temp.substring(0,temp.length()-1));
}
}
}
public static void main(String[] args){
new Calculator();
}}
operation = new JTextField("0");
operation.setEditable(false);
这里的operation.setEditable 什么意思呢
if (equaled)
storedNumber = 0;
for (int i = 0; i < 10; i++)
if (btn == numbers[i])
{
if (operation.getText().equals("0"))
operation.setText("" + i);
else if(! operated)
operation.setText(operation.getText() + i);
else
{
operation.setText("" + i);
operated = false;
}
}
if (btn == dot && ! dotExist)
{
operation.setText(operation.getText() + ".");
dotExist = true;
}
}
}
1这段中按下等于后storedNumber = 0; 这个是结果吗
2if (operation.getText().equals("0")) 这个用法是说当前窗口为0吗
3else if(! operated) 是什么意思呢!号的写法起什么作用呢
4这段代码是在讲输出的事吗? 还有一段的一句
// 进行运算的方法
private void operate(char operator)
{
double currentNumber = Double.valueOf(operation.getText()).doubleValue();
if (lastOperator == '?')
这几句讲的是什么
1、界面制作
2、事件处理
这里的operation.setEditable 什么意思呢
把结果栏设置为不可编辑状态,只能显示用1这段中按下等于后storedNumber = 0; 这个是结果吗
private double storedNumber; // 目前的结果
当上一次按得按钮是equal 或者 changePN或者sqrt的时候
operated会被设置为true,这个时候因为已经有最终结果了,所以下次再按数字键的时候要把
目前的结果初始化,也就是归02if (operation.getText().equals("0")) 这个用法是说当前窗口为0吗
结果栏内容为03else if(! operated) 是什么意思呢!号的写法起什么作用呢
private boolean dotExist, operated, equaled; // 帮助运算的布尔变量
operated是布尔变量,!operated表示operated==false
4这段代码是在讲输出的事吗?
这段代码讲的是按数字键的时候进行的处理还有一段的一句
// 进行运算的方法
private void operate(char operator)
{
double currentNumber = Double.valueOf(operation.getText()).doubleValue();
if (lastOperator == '?')
这几句讲的是什么
把currentNumber设置为Double类型
好多代码我有点看不懂
这个还可以
一般计算器的构成:
一个显示区域 1.10个数字按钮 .和小数点 2.+-*/ 4个算符按 3. CE/C(清空键) 功能键 4.+/-转换 5.=
思路是对按钮侦听,把事件流按上面的方法分为5组,用if分支来实现
如果按了数字/. 就当作字符连接保存在临时变量中(String temp),直到按到 4个算符之一时,就分别保存 前面的表示按过的数字的字符串和 算符(比如存在 str1 和operator中),然后清空temp变量,再等待输入数字 当遇到=号时, 将
temp 和str1 转化为int/Double,将两数按operator中的算符进行计算,放到文本区域上去.... 1.构造界面.
2.对各个按钮实现ActionListener
3.重写ActionListener方法,在此方法中实现上面说的...
这个构成顺序我能理解 甚至也想这么做 但是我疑惑在监听上 这个方法与你给代码满像的吧 但是在事件上时不同的吧
事件流要怎么写呢
显示计算结果的时候要有可能是小数,所以转成double
思路是对按钮侦听,把事件流按上面的方法分为5组,用if分支来实现 你是说这个,其实这个代码就是这么做的,完全符合这个思路,ActionListener 就是动作监听的意思,
所谓事件流说白了就是按了哪个按钮就做对应的操作。
用在学其他的东西上呢!
如果是做swing的话上面已经说的很详细了
如果是网页的话原理也差不多!自己到网上搜一下就会有很多
1. import java.awt.*;
2. import java.awt.event.*;
3. import javax.swing.*;
4.
5. public class Calculator
6. {
7. public static void main(String[] args)
8. {
9. CalculatorFrame frame = new CalculatorFrame();
10. frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
11. frame.setVisible(true);
12. }
13. }
14.
15. /**
16. A frame with a calculator panel.
17. */
18. class CalculatorFrame extends JFrame
19. {
20. public CalculatorFrame()
21. {
22. setTitle("Calculator");
23. CalculatorPanel panel = new CalculatorPanel();
24. add(panel);
25. pack();
26. }
27. }
28.
29. /**
30. A panel with calculator buttons and a result display.
31. */
32. class CalculatorPanel extends JPanel
33. {
34. public CalculatorPanel()
35. {
36. setLayout(new BorderLayout());
37.
38. result = 0;
39. lastCommand = "=";
40. start = true;
41.
42. // add the display
43.
44. display = new JButton("0");
45. display.setEnabled(false);
46. add(display, BorderLayout.NORTH);
47.
48. ActionListener insert = new InsertAction();
49. ActionListener command = new CommandAction();
50.
51. // add the buttons in a 4 x 4 grid
52.
53. panel = new JPanel();
54. panel.setLayout(new GridLayout(4, 4));
55.
56. addButton("7", insert);
57. addButton("8", insert);
58. addButton("9", insert);
59. addButton("/", command);
60.
61. addButton("4", insert);
62. addButton("5", insert);
63. addButton("6", insert);
64. addButton("*", command);
65.
66. addButton("1", insert);
67. addButton("2", insert);
68. addButton("3", insert);
69. addButton("-", command);
70.
71. addButton("0", insert);
72. addButton(".", insert);
73. addButton("=", command);
74. addButton("+", command);
75.
76. add(panel, BorderLayout.CENTER);
77. }
78.
79. /**
80. Adds a button to the center panel.
81. @param label the button label
82. @param listener the button listener
83. */
84. private void addButton(String label, ActionListener listener)
85. {
86. JButton button = new JButton(label);
87. button.addActionListener(listener);
88. panel.add(button);
89. }
90.
91. /**
92. This action inserts the button action string to the
93. end of the display text.
94. */
95. private class InsertAction implements ActionListener
96. {
97. public void actionPerformed(ActionEvent event)
98. {
99. String input = event.getActionCommand();
100. if (start)
101. {
102. display.setText("");
103. start = false;
104. }
105. display.setText(display.getText() + input);
106. }
107. }
108.
109. /**
110. This action executes the command that the button
111. action string denotes.
112. */
113. private class CommandAction implements ActionListener
114. {
115. public void actionPerformed(ActionEvent event)
116. {
117. String command = event.getActionCommand();
118.
119. if (start)
120. {
121. if (command.equals("-"))
122. {
123. display.setText(command);
124. start = false;
125. }
126. else
127. lastCommand = command;
128. }
129. else
130. {
131. calculate(Double.parseDouble(display.getText()));
132. lastCommand = command;
133. start = true;
134. }
135. }
136. }
137.
138. /**
139. Carries out the pending calculation.
140. @param x the value to be accumulated with the prior result.
141. */
142. public void calculate(double x)
143. {
144. if (lastCommand.equals("+")) result += x;
145. else if (lastCommand.equals("-")) result -= x;
146. else if (lastCommand.equals("*")) result *= x;
147. else if (lastCommand.equals("/")) result /= x;
148. else if (lastCommand.equals("=")) result = x;
149. display.setText("" + result);
150. }
151.
152. private JButton display;
153. private JPanel panel;
154. private double result;
155. private String lastCommand;
156. private boolean start;
157. }
package boom;
import javax.swing.*;
import javax.swing.border.Border;
import java.awt.*;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.HashMap;
/**
* 我的计算器。MyCalculator 继承于 JFrame,是计算器的界面
*/
public class MyCalculator extends JFrame {
private static final long serialVersionUID = 1L; private Border border = BorderFactory.createEmptyBorder(5, 5, 5, 5);
private JTextField textbox = new JTextField("0");
private CalculatorCore core = new CalculatorCore();
private ActionListener listener = new ActionListener() {
public void actionPerformed(ActionEvent e) {
JButton b = (JButton) e.getSource();
String label = b.getText();
String result = core.process(label);
textbox.setText(result);
}
};
public MyCalculator(String title) throws HeadlessException {
super(title); // 调用父类构造方法
setupFrame(); // 调整窗体属性
setupControls(); // 创建控件
}
private void setupControls() {
setupDisplayPanel(); // 创建文本面板
setupButtonsPanel(); // 创建按钮面板
}
// 创建按钮面板并添加按钮
private void setupButtonsPanel() {
JPanel panel = new JPanel();
panel.setBorder(border);
panel.setLayout(new GridLayout(4, 5, 3, 3));
createButtons(panel, new String[]{
"7", "8", "9", "+", "C",
"4", "5", "6", "-", "CE",
"1", "2", "3", "*", "", // 空字符串表示这个位置没有按钮
"0", ".", "=", "/", ""
});
this.add(panel, BorderLayout.CENTER);
}
/**
* 在指定的面板上创建按钮
*
* @param panel 要创建按钮的面板
* @param labels 按钮文字
*/
private void createButtons(JPanel panel, String[] labels) {
for (String label : labels) {
// 如果 label 为空,则表示创建一个空面板。否则创建一个按钮。
if (label.equals("")) {
panel.add(new JPanel());
} else {
JButton b = new JButton(label);
b.addActionListener(listener); // 为按钮添加侦听器
panel.add(b);
}
}
}
// 设置显示面板,用一个文本框来作为计算器的显示部分。
private void setupDisplayPanel() {
JPanel panel = new JPanel();
panel.setLayout(new BorderLayout());
panel.setBorder(border);
setupTextbox();
panel.add(textbox, BorderLayout.CENTER);
this.add(panel, BorderLayout.NORTH);
}
// 调整文本框
private void setupTextbox() {
textbox.setHorizontalAlignment(JTextField.RIGHT); // 文本右对齐
textbox.setEditable(false); // 文本框只读
textbox.setBackground(Color.white); // 文本框背景色为白色
}
// 调整窗体
private void setupFrame() {
this.setDefaultCloseOperation(EXIT_ON_CLOSE); // 当窗体关闭时程序结束
this.setLocation(100, 50); // 设置窗体显示在桌面上的位置
this.setSize(300, 200); // 设置窗体大小
this.setResizable(false); // 窗体大小固定
}
// 程序入口
public static void main(String[] args) throws Exception {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
MyCalculator frame = new MyCalculator("我的计算器");
frame.setVisible(true); // 在桌面上显示窗体
}
}
}
/**
* 计算器核心逻辑。这个逻辑只能处理 1~2 个数的运算。
*/
class CalculatorCore {
private String displayText = "0"; // 要显示的文本
boolean reset = true;
private BigDecimal number1, number2;
private String operator;
private HashMap<String, Operator> operators = new HashMap<String, Operator>();
private HashMap<String, Processor> processors = new HashMap<String, Processor>();
CalculatorCore() {
setupOperators();
setupProcessors();
}
// 为每种命令添加处理方式
private void setupProcessors() {
processors.put("[0-9]", new Processor() {
public void calculate(String command) {
numberClicked(command);
}
});
processors.put("\\.", new Processor() {
public void calculate(String command) {
dotClicked();
}
});
processors.put("=", new Processor() {
public void calculate(String command) {
equalsClicked();
}
});
processors.put("[+\\-*/]", new Processor() {
public void calculate(String command) {
operatorClicked(command);
}
});
processors.put("C", new Processor() {
public void calculate(String command) {
clearClicked();
}
});
processors.put("CE", new Processor() {
public void calculate(String command) {
clearErrorClicked();
}
});
}
// 为每种 operator 添加处理方式
private void setupOperators() {
operators.put("+", new Operator() {
public BigDecimal process(BigDecimal number1, BigDecimal number2) {
return number1.add(number2);
}
});
operators.put("-", new Operator() {
public BigDecimal process(BigDecimal number1, BigDecimal number2) {
return number1.subtract(number2);
}
});
operators.put("*", new Operator() {
public BigDecimal process(BigDecimal number1, BigDecimal number2) {
return number1.multiply(number2);
}
});
operators.put("/", new Operator() {
public BigDecimal process(BigDecimal number1, BigDecimal number2) {
return number1.divide(number2, 30, RoundingMode.HALF_UP);
}
});
}
// 根据命令处理。这里的命令实际上就是按钮文本。
public String process(String command) {
for (String pattern : processors.keySet()) {
if (command.matches(pattern)) {
processors.get(pattern).calculate(command);
break;
}
}
return displayText;
}
// 当按下 CE 时
private void clearErrorClicked() {
if (operator == null) {
number1 = null;
} else {
number2 = null;
}
displayText = "0";
reset = true;
}
// 当按下 C 时,将计算器置为初始状态。
private void clearClicked() {
number1 = null;
number2 = null;
operator = null;
displayText = "0";
reset = true;
}
// 当按下 = 时
private void equalsClicked() {
calculateResult();
number1 = null;
number2 = null;
operator = null;
reset = true;
}
// 计算结果
private void calculateResult() {
number2 = new BigDecimal(displayText);
Operator oper = operators.get(operator);
if (oper != null) {
BigDecimal result = oper.process(number1, number2);
displayText = result.toString();
}
}
// 当按下 +-*/ 时(这里也可以扩展成其他中间操作符)
private void operatorClicked(String command) {
if (operator != null) {
calculateResult();
}
number1 = new BigDecimal(displayText);
operator = command;
reset = true;
}
// 当按下 . 时
private void dotClicked() {
if (displayText.indexOf(".") == -1) {
displayText += ".";
} else if (reset) {
displayText = "0.";
}
reset = false;
}
// 当按下 0-9 时
private void numberClicked(String command) {
if (reset) {
displayText = command;
} else {
displayText += command;
}
reset = false;
}
// 运算符处理接口
interface Operator {
BigDecimal process(BigDecimal number1, BigDecimal number2);
}
// 按钮处理接口
interface Processor {
void calculate(String command);
}