java 简易计算器(帮我改一改,增加几个功能)

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java 简易计算器(帮我改一改,增加几个功能)相关的知识,希望对你有一定的参考价值。

源代码如下:增加归零、删除、正负之间的切换、数字的取整
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class Calculator extends JFrame
public Calculator()
setTitle("简易计算器");
setSize(400,300);
CalculatorPanel panel=new CalculatorPanel();
add(panel);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);


public static void main(String[] args)
new Calculator();



class CalculatorPanel extends JPanel
JTextField display;//显示屏幕
JPanel panel;//控制面板
double result;//显示结果
String lastCommand;//触发程序进行计算的按键
boolean start;//控制开始开关

public CalculatorPanel()
setLayout(new BorderLayout());

result=0;//设置初始结果为0
lastCommand="=";
start=true;

display=new JTextField("0");//设置文本框为0
display.setEnabled(false);
add(display,BorderLayout.NORTH);//在北面显示计算结果

ActionListener insert=new InsertAction();//数字输入监听者
ActionListener command=new CommandAction();//计算符号监听者

panel=new JPanel();
panel.setLayout(new GridLayout(5,4));//设置5*4网格面板

addButton("取整",command);
addButton("+/-",command);
addButton("<-",command);
addButton("C",command);

addButton("7",insert);
addButton("8",insert);
addButton("9",insert);
addButton("/",command);

addButton("4",insert);
addButton("5",insert);
addButton("6",insert);
addButton("*",command);

addButton("1",insert);
addButton("2",insert);
addButton("3",insert);
addButton("-",command);

addButton("0",insert);
addButton(".",insert);
addButton("=",command);
addButton("+",command);

add(panel,BorderLayout.CENTER);


private void addButton(String label,ActionListener listener)
JButton button=new JButton(label);
button.addActionListener(listener);
panel.add(button);


private class InsertAction implements ActionListener
public void actionPerformed(ActionEvent event)

String input=event.getActionCommand();
if(start)
display.setText("");
start=false;

display.setText(display.getText()+input);



private class CommandAction implements ActionListener
public void actionPerformed(ActionEvent event)
String command=event.getActionCommand();

if(start)
if(command.equals("-"))
display.setText(command);
start=false;

else lastCommand=command;

else

calculator(Double.parseDouble(display.getText()));
lastCommand=command;
start=true;




public void calculator(double x)
if(lastCommand.equals("+")) result+=x;
else if(lastCommand.equals("-")) result-=x;
else if(lastCommand.equals("*")) result*=x;
else if(lastCommand.equals("/")) result/=x;
else if(lastCommand.equals("=")) result=x;
display.setText(""+result);

参考技术A package com.sh.lw.bean;

import java.util.Map;

public class ErrorMessage

private Map<String, String> error1;

public Map<String, String> getError1()
return error1;


public void setError1(Map<String, String> error1)
this.error1 = error1;




package com.sh.lw.bean;

public class User

private String username;
private String password;

public String getUsername()
return username;


public void setUsername(String username)
this.username = username;


public String getPassword()
return password;


public void setPassword(String password)
this.password = password;




package com.sh.lw.bean.business;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.sh.lw.bean.ErrorMessage;
import com.sh.lw.bean.User;
import com.sh.lw.bean.dao.UserDao;

public class CheckLogin

public void isLogin(User u, HttpServletRequest request, HttpServletResponse resp)
Map<String, String> map = new HashMap<String, String>();
ErrorMessage em = new ErrorMessage();
em.setError1(map);
if (u.getUsername().equals("") || u.getPassword().equals(""))
map.put("error2", "用户名或密码不能为空!");
try
request.getRequestDispatcher("/index.jsp").forward(request, resp);
catch (ServletException e)
// TODO Auto-generated catch block
e.printStackTrace();
catch (IOException e)
// TODO Auto-generated catch block
e.printStackTrace();


UserDao dao = new UserDao();
List<User> list = dao.queryUser(u);
if (list.size() < 1)
try

map.put("error1", "用户名或密码错误!");

request.setAttribute("error1", map);
request.setAttribute("user", u);
request.getRequestDispatcher("/index.jsp").forward(request, resp);
catch (ServletException e)
// TODO Auto-generated catch block
e.printStackTrace();
catch (IOException e)
// TODO Auto-generated catch block
e.printStackTrace();





package com.sh.lw.bean.business;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class CountBusiness

private String flag;
private String var1;
private String var2;
private String operat;

public String count(HttpServletRequest request, HttpServletResponse response)
String result0 = "";
Double result = null;
if (flag != null)
if (flag.equals("1"))

if (var1 == null || var1.equals(""))
return null;
if (var2 == null || var2.equals(""))
return null;
if (operat == null || operat.equals(""))
return null;

var1 = var1.trim();
var2 = var2.trim();
operat = operat.trim();
double var10 = 0.0;
double var20 = 0.0;
try
var10 = Double.parseDouble(var1);
var20 = Double.parseDouble(var2);
catch (java.lang.NumberFormatException e)
request.setAttribute("flag0", "");
request.setAttribute("falg2", "3");
request.setAttribute("error_code", "只能输入数字类型!");
try
request.getRequestDispatcher("/welcome.jsp").forward(request, response);
catch (ServletException e1)
// TODO Auto-generated catch block
e1.printStackTrace();
catch (IOException e1)
// TODO Auto-generated catch block
e1.printStackTrace();



if (operat != null)
if (operat.equals("+"))
result = var10 + var20;
else if (operat.equals("-"))
result = var10 - var20;
else if (operat.equals("*"))
result = var10 * var20;
else if (operat.equals("/"))
result = var10 / var20;

result0 = String.valueOf(result);


return result0;


public String getFlag()
return flag;


public void setFlag(String flag)
this.flag = flag;


public String getVar1()
return var1;


public void setVar1(String var1)
this.var1 = var1;


public String getVar2()
return var2;


public void setVar2(String var2)
this.var2 = var2;


public String getOperat()
return operat;


public void setOperat(String operat)
this.operat = operat;



package com.sh.lw.bean.dao;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class DB

private final String username = "root";
private final String password = "";
private final String conUrl = "jdbc:mysql://localhost/test";
private Connection conn;

public Connection getConn()
return conn;


public void setConn(Connection conn)
this.conn = conn;


public DB()
try
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection(conUrl, username, password);
catch (SQLException e)
// TODO Auto-generated catch block
e.printStackTrace();
catch (ClassNotFoundException e)
// TODO Auto-generated catch block
e.printStackTrace();





package com.sh.lw.bean.dao;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import com.sh.lw.bean.User;

public class UserDao

public List queryUser(User u)
String sql = "select * from user u where u.username=? and u.password=?";
List list = new ArrayList<User>();
;
try
PreparedStatement pstmt = new DB().getConn().prepareStatement(sql);
pstmt.setString(1, u.getUsername());
pstmt.setString(2, u.getPassword());
ResultSet rs = pstmt.executeQuery();
while (rs.next())
User uu = new User();
uu.setUsername(rs.getString(2));
uu.setPassword(rs.getString(3));
list.add(uu);

catch (SQLException e)
// TODO Auto-generated catch block
e.printStackTrace();

return list;



-->index.jsp
<%@ page language="java" import="java.util.*" pageEncoding="gbk"%>
<%@ page import="com.sh.lw.bean.User" %>
<%@ page import="com.sh.lw.bean.ErrorMessage" %>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">

<title>My JSP 'index.jsp' starting page</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
<script type="text/javascript">
function checkForm(obj)
var username = obj.username.value;
var pass = obj.password.value;
if(username==null||username=="")

alert("请输入用户名!");
return false;


if(pass==null||pass=="")

alert("请输入密码!");
return false;



</script>
</head>

<body>

<%
User user = (User)request.getAttribute("user");
String username="";
String password="";
if(user!=null)
username=user.getUsername();
if(username==null)
username="";
password=user.getPassword();
if(password==null)
password="";

%>
<form action="welcome.jsp" onsubmit="return checkForm(this)">
用户名:<input name="username" value="<%=username%>"/>
<br/>密码:<input name="password" value="<%=password%>"/>
</br><input type="submit" value="提交"/>
</form>

<%
Map<String,String> map = (HashMap<String,String>)request.getAttribute("error1");
String message0="";
String message2="";
if(map!=null)
message0 = map.get("error1");
message2 = map.get("error2");
if(message2==null)
message2="";

%>
<font color="red"><%=message0 %>
<br/>
<%=message2 %>
</font>
</body>
</html>

-->welcome.jsp
<%@page contentType="text/html;charset=gbk" %>
<jsp:useBean id="user" class="com.sh.lw.bean.User">
<jsp:setProperty name="user" property="*"/>
</jsp:useBean>

<jsp:useBean id="checkLogin" class="com.sh.lw.bean.business.CheckLogin">
<jsp:setProperty name="checkLogin" property="*"/>
</jsp:useBean>

<jsp:useBean id="count" class="com.sh.lw.bean.business.CountBusiness">
<jsp:setProperty name="count" property="*"/>
</jsp:useBean>
<script type="text/javascript">
function checkForm(obj)
var va1 = obj.var1.value;
var var2 = obj.var2.value;
var operat = obj.operat.value;
if(va1==null||va1=="")

alert("参数1不能为空!");
return false;


if(var2==null||var2=="")

alert("参数2不能为空!");
return false;


if(operat==null||operat=="")

alert("操作符不能为空!");
return false;



</script>

<%
String flag = request.getParameter("flag");
String flag0 = request.getParameter("flag0");
String falg2=(String)request.getAttribute("falg2");
String result0="";
if(falg2!=null&&falg2.equals("3"))

String errorcode = (String)request.getAttribute("error_code");
%>
<font color="red"><%=errorcode %></font>
<%

else if(flag0!=null&&flag0.equals("1"))

;
else if(flag!=null)
if(flag.equals("1"))

flag="0";
result0 = count.count(request,response);

%>
<h3>简易计算器</h3>

<%
else
checkLogin.isLogin(user,request,response);
%>
登录成功
<%
%>

<form action="welcome.jsp" method="post" onsubmit="return checkForm(this)">
<input name="var1" value="<%=request.getParameter("var1") %>"/>
<select name="operat" >
<option value="+">+</option>
<option value="-">-</option>
<option value="*">*</option>
<option value="/">/</option>
</select>
<input name="var2" value="<%=request.getParameter("var2") %>"/>
=
<input name="result" value="<%= result0%>" onsubmit="return checkForm(this)"/>
</br></br>
<center><input type="submit" value="计算"/></center>
<input type="hidden" name="flag" value="1">
</form>

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.4"
xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>

里面有登陆,然后进入计算器界面 ,你要导入jdbc的jar包,才能使用
下面是建表语句
use test;
create table user(id int primary key AUTO_INCREMENT,username varchar(30),password varchar(2));
insert into user values('1','admin','admin');
commit;
初始用户名和密码是admin admin本回答被提问者采纳

帮我写一个简易的strcmp函数(C语言)。

帮我用最简单的代码写一个strcmp程序。
然后告诉我strcmp的返回值代表什么?

① c的strcmp简洁实现可以是这样的:

int strcmp(const char* s1, const char* s2)

    while(*s1 && (*s1==*s2))
        s1++,s2++;
    return *(const unsigned char*)s1-*(const unsigned char*)s2;

② strcmp的返回值可以有3种,即<0, =0, >0 (任意一个数值),代表的含义分别是: str1 strcmp用的是二进制比较,意思是按字典顺序,比如: 字母a < 字母 b;而a > A。 (这是因为a的ascii码是97,而A的是65)。

理解了这个,上面的代码就好理解了。 while就是s1,s2从头到位一个一个字符的比较。如果s1为空,或者s1不等于s2,则中断循环 (s1不为空,s2为空,则是*s1 != *s2,退出循环)。返回值是循环中断时的字符(分别s1和s2对应的位置,*s1-*s2, 如果是上面说的 'a' - 'A', 那么返回的就是97-65=32),那么意味着a在A前面, strcmp > 0。

之所以先转换成const unsigned char*再作减法,是由于c的char有三种: char, signed char 和unsigned char。 char就是'a'这样的, 而 signed char 则是-127~126之间的数值,而unsigned char则是0~255之间的一个值。 转换成unsigned char就是要“确保” 'a' ---> 97。 你要不转换,也是可以的。

说明一点,很多c的lib实现,比如gnu c, 都是把结果处理成: -1, 0, 1, 而不是这个字符对应的ascii码的差值。

参考技术A int strcmp_s(char *src,char*des)
if(src==NULL||des==NULL) return NULL;
while((*src++==*des++)!='\\0');
if(*src=='\\0') return 0;
return (*src-*des);

追问

复制勿扰

以上是关于java 简易计算器(帮我改一改,增加几个功能)的主要内容,如果未能解决你的问题,请参考以下文章

cf之kmp匹配稍稍改一改

AI「抄」代码无罪?GitHub Copilot拿用户的开源代码改一改就去挣钱!

2018暑假第四周总结(7.30-8.5)

如何修改CSS样式表?

文件下载和预览

JSP运行时505错误,麻烦帮我改好