导航:首页 > 编程语言 > java案例源代码

java案例源代码

发布时间:2024-07-10 00:39:37

❶ 帮忙给一个java菜单栏例子的源代码

给你个小例子,已经添加注释了。自己运行下看看效果,满意的话记得结贴子!
import java.awt.BorderLayout;
import java.awt.CheckboxMenuItem;
import java.awt.Frame;
import java.awt.Menu;
import java.awt.MenuBar;
import java.awt.MenuItem;
import java.awt.TextArea;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

public class TestMenu extends Frame implements ActionListener{
TextArea ta; //文本区
MenuBar mb; //MenuBar 类封装绑定到框架的菜单栏的
Menu mnFile,mnEdit,mnFormat,mnHelp; //从菜单栏部署的下拉式菜单组件
MenuItem miNew,miOpen,miSave,miSaveAs,miExit,miFont; //菜单中的所有项必须属于类 MenuItem 或其子类之一
CheckboxMenuItem miBinary; //一个可包括在菜单中的复选框
public TestMenu(){
super("记事本"); //调用父类构造方法
ta = new TextArea("",20,20); //新建文本区,第一个参数是默认文本,第二个参数是行数,第三个是列数
/*
* BorderLayout边框布局
* 添加文本区到Frame,BorderLayout.CENTER是居中位置
* */
add(ta,BorderLayout.CENTER);
mb = new MenuBar(); //创建菜单栏对象
/*
* 创建菜单,指定菜单名
* */
mnFile= new Menu("文件");
mnEdit= new Menu("编辑");
mnFormat= new Menu("格式");
mnHelp= new Menu("帮助");

/*
* 创建子菜单,并指定名称
* */
miNew= new MenuItem("新建");
miOpen= new MenuItem("打开");
miSave= new MenuItem("保存");
miSaveAs= new MenuItem("另存为");
miExit= new MenuItem("退出");

miExit.addActionListener(this); //为退出菜单添加监听

/*
* 添加上面创建的子菜单到文件菜单下
* */
mnFile.add(miNew);
mnFile.add(miOpen);
mnFile.add(miSave);
mnFile.add(miSaveAs);
mnFile.addSeparator(); //将一个分隔线或连字符添加到菜单的当前位置
mnFile.add(miExit);

miBinary= new CheckboxMenuItem("二进制"); //创建在复选框的子菜单
miFont= new MenuItem("字体"); //创建子菜单
/*
* 添加miBinary、miFont两个子菜单到mnFormat(格式)下
* */
mnFormat.add(miBinary);
mnFormat.add(miFont);

/*
* 将文件、编辑、格式、帮助添加到菜单栏
* */
mb.add(mnFile);
mb.add(mnEdit);
mb.add(mnFormat);
mb.add(mnHelp);

setMenuBar(mb); //添加菜单栏到Frame

/*
* 关闭窗口时,关闭运行成语
* */
addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e){
System.exit(0);
}
});
}
public static void main(String args[]){
TestMenu tm=new TestMenu();
tm.setSize(300,200); //设置窗体的宽、高
tm.setLocation(300,100); //将组件移到新位置Component类方法
tm.setVisible(true); //设置显示窗体,true为显示,false为隐藏
}

/**
* 监听事件,实现ActionListener接口的actionPerformed方法
*/
public void actionPerformed(ActionEvent e){
String s = e.getActionCommand(); //获取选中菜单的名称
System.out.println(s);
if(s.equals("退出")){
System.exit(0); //停止运行程序
}
}
}

❷ 求:java实例源代码

import java.awt.*;
import java.awt.event.*;
import java.lang.*;
import javax.swing.*;
public class Counter extends Frame
{
//声明三个面板的布局
GridLayout gl1,gl2,gl3;
Panel p0,p1,p2,p3;
JTextField tf1;
TextField tf2;
Button b0,b1,b2,b3,b4,b5,b6,b7,b8,b9,b10,b11,b12,b13,b14,b15,b16,b17,b18,b19,b20,b21,b22,b23,b24,b25,b26;
StringBuffer str;//显示屏所显示的字符串
double x,y;//x和y都是运算数
int z;//Z表示单击了那一个运算符.0表示"+",1表示"-",2表示"*",3表示"/"
static double m;//记忆的数字
public Counter()
{
gl1=new GridLayout(1,4,10,0);//实例化三个面板的布局
gl2=new GridLayout(4,1,0,15);
gl3=new GridLayout(4,5,10,15);

tf1=new JTextField(27);//显示屏
tf1.setHorizontalAlignment(JTextField.RIGHT);
tf1.setEnabled(false);
tf1.setText("0");
tf2=new TextField(10);//显示记忆的索引值
tf2.setEditable(false);
//实例化所有按钮、设置其前景色并注册监听器
b0=new Button("Backspace");
b0.setForeground(Color.red);
b0.addActionListener(new Bt());
b1=new Button("CE");
b1.setForeground(Color.red);
b1.addActionListener(new Bt());
b2=new Button("C");
b2.setForeground(Color.red);
b2.addActionListener(new Bt());
b3=new Button("MC");
b3.setForeground(Color.red);
b3.addActionListener(new Bt());
b4=new Button("MR");
b4.setForeground(Color.red);
b4.addActionListener(new Bt());
b5=new Button("MS");
b5.setForeground(Color.red);
b5.addActionListener(new Bt());
b6=new Button("M+");
b6.setForeground(Color.red);
b6.addActionListener(new Bt());
b7=new Button("7");
b7.setForeground(Color.blue);
b7.addActionListener(new Bt());
b8=new Button("8");
b8.setForeground(Color.blue);
b8.addActionListener(new Bt());
b9=new Button("9");
b9.setForeground(Color.blue);
b9.addActionListener(new Bt());
b10=new Button("/");
b10.setForeground(Color.red);
b10.addActionListener(new Bt());
b11=new Button("sqrt");
b11.setForeground(Color.blue);
b11.addActionListener(new Bt());
b12=new Button("4");
b12.setForeground(Color.blue);
b12.addActionListener(new Bt());
b13=new Button("5");
b13.setForeground(Color.blue);
b13.addActionListener(new Bt());
b14=new Button("6");
b14.setForeground(Color.blue);
b14.addActionListener(new Bt());
b15=new Button("*");
b15.setForeground(Color.red);
b15.addActionListener(new Bt());
b16=new Button("%");
b16.setForeground(Color.blue);
b16.addActionListener(new Bt());
b17=new Button("1");
b17.setForeground(Color.blue);
b17.addActionListener(new Bt());
b18=new Button("2");
b18.setForeground(Color.blue);
b18.addActionListener(new Bt());
b19=new Button("3");
b19.setForeground(Color.blue);
b19.addActionListener(new Bt());
b20=new Button("-");
b20.setForeground(Color.red);
b20.addActionListener(new Bt());
b21=new Button("1/X");
b21.setForeground(Color.blue);
b21.addActionListener(new Bt());
b22=new Button("0");
b22.setForeground(Color.blue);
b22.addActionListener(new Bt());
b23=new Button("+/-");
b23.setForeground(Color.blue);
b23.addActionListener(new Bt());
b24=new Button(".");
b24.setForeground(Color.blue);
b24.addActionListener(new Bt());
b25=new Button("+");
b25.setForeground(Color.red);
b25.addActionListener(new Bt());
b26=new Button("=");
b26.setForeground(Color.red);
b26.addActionListener(new Bt());

//实例化四个面板
p0=new Panel();
p1=new Panel();
p2=new Panel();
p3=new Panel();
//创建一个空字符串缓冲区
str=new StringBuffer();

//添加面板p0中的组件和设置其在框架中的位置和大小
p0.add(tf1);
p0.setBounds(10,25,300,40);
//添加面板p1中的组件和设置其在框架中的位置和大小
p1.setLayout(gl1);
p1.add(tf2);
p1.add(b0);
p1.add(b1);
p1.add(b2);
p1.setBounds(10,65,300,25);
//添加面板p2中的组件并设置其的框架中的位置和大小
p2.setLayout(gl2);
p2.add(b3);
p2.add(b4);
p2.add(b5);
p2.add(b6);
p2.setBounds(10,110,40,150);
//添加面板p3中的组件并设置其在框架中的位置和大小
p3.setLayout(gl3);//设置p3的布局
p3.add(b7);
p3.add(b8);
p3.add(b9);
p3.add(b10);
p3.add(b11);
p3.add(b12);
p3.add(b13);
p3.add(b14);
p3.add(b15);
p3.add(b16);
p3.add(b17);
p3.add(b18);
p3.add(b19);
p3.add(b20);
p3.add(b21);
p3.add(b22);
p3.add(b23);
p3.add(b24);
p3.add(b25);
p3.add(b26);
p3.setBounds(60,110,250,150);
//设置框架中的布局为空布局并添加4个面板
setLayout(null);
add(p0);
add(p1);
add(p2);
add(p3);
setResizable(false);//禁止调整框架的大小
//匿名类关闭窗口
addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e1)
{
System.exit(0);
}
});
setBackground(Color.lightGray);
setBounds(100,100,320,280);
setVisible(true);

}
//构造监听器
class Bt implements ActionListener
{
public void actionPerformed(ActionEvent e2)
{
try{

if(e2.getSource()==b1)//选择"CE"清零
{
tf1.setText("0");//把显示屏清零
str.setLength(0);//清空字符串缓冲区以准备接收新的输入运算数
}
else if(e2.getSource()==b2)//选择"C"清零
{
tf1.setText("0");//把显示屏清零
str.setLength(0);
}
else if(e2.getSource()==b23)//单击"+/-"选择输入的运算数是正数还是负数
{
x=Double.parseDouble(tf1.getText().trim());
tf1.setText(""+(-x));
}
else if(e2.getSource()==b25)//单击加号按钮获得x的值和z的值并清空y的值
{
x=Double.parseDouble(tf1.getText().trim());
str.setLength(0);//清空缓冲区以便接收新的另一个运算数
y=0d;
z=0;
}
else if(e2.getSource()==b20)//单击减号按钮获得x的值和z的值并清空y的值
{
x=Double.parseDouble(tf1.getText().trim());
str.setLength(0);
y=0d;
z=1;
}
else if(e2.getSource()==b15)//单击乘号按钮获得x的值和z的值并清空y的值
{
x=Double.parseDouble(tf1.getText().trim());
str.setLength(0);
y=0d;
z=2;
}
else if(e2.getSource()==b10)//单击除号按钮获得x的值和z的值并空y的值
{
x=Double.parseDouble(tf1.getText().trim());
str.setLength(0);
y=0d;
z=3;
}
else if(e2.getSource()==b26)//单击等号按钮输出计算结果
{
str.setLength(0);
switch(z)
{
case 0 : tf1.setText(""+(x+y));break;
case 1 : tf1.setText(""+(x-y));break;
case 2 : tf1.setText(""+(x*y));break;
case 3 : tf1.setText(""+(x/y));break;
}
}
else if(e2.getSource()==b24)//单击"."按钮输入小数
{
if(tf1.getText().trim().indexOf(′.′)!=-1)//判断字符串中是否已经包含了小数点
{

}
else//如果没数点有小
{
if(tf1.getText().trim().equals("0"))//如果初时显示为0
{
str.setLength(0);
tf1.setText((str.append("0"+e2.getActionCommand())).toString());
}
else if(tf1.getText().trim().equals(""))//如果初时显示为空则不做任何操作
{
}
else
{
tf1.setText(str.append(e2.getActionCommand()).toString());
}
}

y=0d;

}
else if(e2.getSource()==b11)//求平方根
{
x=Double.parseDouble(tf1.getText().trim());
tf1.setText("数字格式异常");
if(x<0)
tf1.setText("负数没有平方根");
else
tf1.setText(""+Math.sqrt(x));
str.setLength(0);
y=0d;
}
else if(e2.getSource()==b16)//单击了"%"按钮
{
x=Double.parseDouble(tf1.getText().trim());
tf1.setText(""+(0.01*x));
str.setLength(0);
y=0d;
}
else if(e2.getSource()==b21)//单击了"1/X"按钮
{

x=Double.parseDouble(tf1.getText().trim());
if(x==0)
{

tf1.setText("除数不能为零");
}
else
{
tf1.setText(""+(1/x));
}
str.setLength(0);
y=0d;
}
else if(e2.getSource()==b3)//MC为清除内存
{
m=0d;
tf2.setText("");
str.setLength(0);
}
else if(e2.getSource()==b4)//MR为重新调用存储的数据
{
if(tf2.getText().trim()!="")//有记忆数字
{
tf1.setText(""+m);
}
}
else if(e2.getSource()==b5)//MS为存储显示的数据
{

m=Double.parseDouble(tf1.getText().trim());
tf2.setText("M");
tf1.setText("0");
str.setLength(0);
}
else if(e2.getSource()==b6)//M+为将显示的数字与已经存储的数据相加要查看新的数字单击MR
{
m=m+Double.parseDouble(tf1.getText().trim());
}
else//选择的是其他的按钮
{
if(e2.getSource()==b22)//如果选择的是"0"这个数字键
{
if(tf1.getText().trim().equals("0"))//如果显示屏显示的为零不做操作
{

}
else
{
tf1.setText(str.append(e2.getActionCommand()).toString());
y=Double.parseDouble(tf1.getText().trim());
}
}
else if(e2.getSource()==b0)//选择的是“BackSpace”按钮
{
if(!tf1.getText().trim().equals("0"))//如果显示屏显示的不是零
{
if(str.length()!=1)
{
tf1.setText(str.delete(str.length()-1,str.length()).toString());//可能抛出字符串越界异常
}
else
{
tf1.setText("0");
str.setLength(0);
}
}
y=Double.parseDouble(tf1.getText().trim());
}
else//其他的数字键
{
tf1.setText(str.append(e2.getActionCommand()).toString());
y=Double.parseDouble(tf1.getText().trim());
}
}
}
catch(NumberFormatException e){
tf1.setText("数字格式异常");
}
catch( e){
tf1.setText("字符串索引越界");
}
}
}
public static void main(String args[])
{
new Counter();
}

}

❸ 求一个简单又经典的Java与数据库例子,要有源代码哦!

//下面的是连接mysql的例子
package com.song.struts.mySql;

import javax.swing.JComponent;
import java.sql.*;
import java.util.*;
// import com.borland.dx.sql.dataset.*;

public class mySqlDao extends JComponent {
private String UserName="root";
private String PWD="root";
private String url;
private Connection cn;
private Statement stmt;
private ResultSet rs = null;
public mySqlDao(){
try {
Class.forName("org.gjt.mm.mysql.Driver");
}
catch(java.lang.ClassNotFoundException e){
System.err.println("mydb() org.gjt.mm.mysql.Driver: " + e.getMessage());
}
catch(Exception e) {
e.printStackTrace();
}

}
//////////////////////////////
///返回mysql 连接,connection
/////////////////////////////
public Connection Connect(String dbname,String ip){
try{
String hostip=ip;
Properties myP = new Properties();
myP.setProperty("useUnicode","true");
myP.setProperty("characterEncoding","GB2312");
url="jdbc:mysql://"+hostip+":3306/"+dbname+"?user="+UserName+"&password="+PWD+"";
if(cn!=null){
cn.close();
}
cn=DriverManager.getConnection(url,myP);
stmt= cn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_UPDATABLE);
System.out.println("db connect success");
return cn;
}
catch(Exception e){
System.err.println("db connect err"+e.getMessage());
return null;
}
}
//////////////////////////////////
///关闭连接
/////////////////////////////////
public void close(){
try{
if(stmt!=null){
stmt.close();
}
if(cn!=null){
cn.close();
}
System.err.println("db colse success");
}
catch(Exception e){
System.err.println("db close err"+e.getMessage());
}
}
/////////////////////////////////////////////
// 用于进行记录的查询操�?,用于select 语句�?
//参数:sql语句�?
//返回:ResultSet对象
///////////////////////////////////////////
public ResultSet executeSelect(String sql) {
try {
stmt=cn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_UPDATABLE);
rs = stmt.executeQuery(sql);
return rs;
}
catch(SQLException ex) {
System.err.println("db.executeQuery: " + ex.getMessage());
return null;
}
}
//////////////////////////////////////////////
//用于进行add或�?�update,insert,del等的记录的操�?,
//入口参数:sql语句
//返回 :true,false
//////////////////////////////////////////////
public boolean executeUpdate(String sql) {
boolean bupdate=false;
try{
stmt=cn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_UPDATABLE);
int rowCount = stmt.executeUpdate(sql);
if (rowCount!=0)
bupdate=true;
}
catch(SQLException ex) {
System.err.println("db.executeUpdate: " + ex.getMessage());
}
return bupdate;
}
//////////////////////////////////////////////
//用于进行表结构的操作,creat drop,modify等�??
//入口参数:sql语句
//返回 :true,false
//////////////////////////////////////////////
public boolean executeTable(String sql) {
boolean bupdate=false;
try {
stmt= cn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_UPDATABLE);
System.out.print("对表的操作的sqlis :||"+sql+"||");
stmt.executeUpdate(sql);
bupdate=true;
}
catch(SQLException ex) {
System.err.println("db.executeTable: "+ex.getMessage());
}
return bupdate;
}
//////////////////////////
//返回数据库的信息
//////////////////////////
public Statement getLWPAIDStatement(){
try{
return cn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_UPDATABLE);
}
catch(java.sql.SQLException e){
System.err.println("getAISPStatement():"+e.getMessage());
return null;
}
}

public DatabaseMetaData getLWPAIDMetaData(){
try{
return cn.getMetaData();
}
catch(java.sql.SQLException e){
System.err.println("getAISPMetaData():"+e.getMessage());
return null;
}
}
public static void main(String args[]){
mySqlDao a=new mySqlDao();
a.Connect("mydb", "localhost");
int b=-100;
ResultSet rs=a.executeSelect("select max(bill_id) from t_bill limit 1");
try{
while(rs.next()){
System.out.println("is in");
b=rs.getInt(1);
}
}catch(Exception e){
e.printStackTrace();
}
System.out.println(b);
// java.util.Date date=new java.util.Date();
// System.out.println(date.toString());
// a.executeTable("insert into t_user values(100,'123','1345')");
// a.executeTable("update t_user set insert_date='"+date.toString()+"' where user_id=100");
a.close();

System.out.print(new pub().asc2unicode("�?!"));
}
}

❹ 高分求两个简单的JAVA设计源代码

上面 wukun12同学写的不错,但我想还不能运行,并且还不太完善。我给个能运行的:(注意:文件名为:Test.java)

//要实现对象间的比较,就必须实现Comparable接口,它里面有个compareTo方法
//Comparable最好使用泛型,这样,无论是速度还是代码量都会减少
@SuppressWarnings("unchecked")
class Student implements Comparable<Student>{

private String studentNo; //学号
private String studentName; //姓名
private double englishScore; //英语成绩
private double computerScore; //计算机成绩
private double mathScore; //数学成绩
private double totalScore; //总成绩

//空构造函数
public Student() {}

//构造函数
public Student(String studentNo,String studentName,double englishSocre,double computerScore,double mathScore) {
this.studentNo = studentNo;
this.studentName = studentName;
this.englishScore = englishSocre;
this.computerScore = computerScore;
this.mathScore = mathScore;
}

//计算总成绩
public double sum() {

this.totalScore = englishScore+computerScore+mathScore;
return totalScore;
}

//计算评测成绩
public double testScore() {

return sum()/3;
}

//实现compareTO方法
@Override
public int compareTo(Student student) {
double studentTotal = student.getTotalScore();
return totalScore==studentTotal?0:(totalScore>studentTotal?1:-1);
}

//重写toString方法
public String toString(){
return "学号:"+this.getStudentNo()+" 姓名:"+this.getStudentName()+" 英语成绩:"+this.getEnglishScore()+" 数学成绩:"+this.getMathScore()+" 计算机成绩:"+this.getComputerScore()+" 总成绩:"+this.getTotalScore();
}

//重写equals方法
public boolean equals(Object obj) {
if(obj == null){
return false;
}
if(!(obj instanceof Student)){
return false;
}
Student student = (Student)obj;
if(this.studentNo.equals(student.getStudentName())) { //照现实来说,比较是不是同一个学生,应该只是看他的学号是不是相同
return true;
} else {
return false;
}

}

/*以下为get和set方法,我个人认为,totalScore的set的方法没必要要,因为它是由其它成绩计算出来的
在set方法中,没设置一次值,调用一次sum方法,即重新计算总成绩
*/
public String getStudentNo() {
return studentNo;
}
public void setStudentNo(String studentNo) {
this.studentNo = studentNo;
sum();
}
public String getStudentName() {
return studentName;
}
public void setStudentName(String studentName) {
this.studentName = studentName;
sum();
}
public double getEnglishScore() {
return englishScore;
}
public void setEnglishScore(double englishScore) {
this.englishScore = englishScore;
sum();
}
public double getComputerScore() {
return computerScore;
}
public void setComputerScore(double computerScore) {
this.computerScore = computerScore;
sum();
}
public double getMathScore() {
return mathScore;
}
public void setMathScore(double mathScore) {
this.mathScore = mathScore;
sum();
}
public double getTotalScore() {
return totalScore;
}

}

//Student子类学习委员类的实现
class StudentXW extends Student {

//重写父类Student的testScore()方法
@Override
public double testScore() {
return sum()/3+3;
}

public StudentXW() {}

//StudentXW的构造函数
public StudentXW(String studentNo,String studentName,double englishSocre,double computerScore,double mathScore) {
super(studentNo,studentName,englishSocre,computerScore,mathScore);
}
}

//Student子类班长类的实现
class StudentBZ extends Student {

//重写父类Student的testScore()方法
@Override
public double testScore() {
return sum()/3+5;
}

public StudentBZ() {}

//StudentXW的构造函数
public StudentBZ(String studentNo,String studentName,double englishSocre,double computerScore,double mathScore) {
super(studentNo,studentName,englishSocre,computerScore,mathScore);
}
}

//测试类
public class Test {

public static void main(String[] args) {

//生成若干个student类、StudentXW类、StudentBZ类
Student student1 = new Student("s001","张三",70.5,50,88.5);
Student student2 = new Student("s002","李四",88,65,88.5);
Student student3 = new Student("s003","王五",67,77,90);
StudentXW student4 = new StudentXW("s004","李六",99,88,99.5);
StudentBZ student5 = new StudentBZ("s005","朱漆",56,65.6,43.5);

Student[] students = {student1,student2,student3,student4,student5};

for(int i = 0 ; i<students.length; i++){
double avgScore = students[i].testScore();
System.out.println(students[i].getStudentName()+"学生的评测成绩为:"+ avgScore+"分");
}

}
}
运行结果为:
张三学生的评测成绩为:69.66666666666667分
李四学生的评测成绩为:80.5分
王五学生的评测成绩为:78.0分
李六学生的评测成绩为:98.5分
朱漆学生的评测成绩为:60.03333333333333分

❺ 求Java高手给一简单的源代码(200行以下),最好有注解和一段简单的介绍

//声明包
package cn.jbit.classandobject;
//导入包
import java.util.Scanner;
/**
* 上机阶段4:登录并购买商品
*/
// 声明类Goods
public class Goods
{
// 声明String类型的数组:goods,并初始化。
String[] goods = new String[] { "电风扇", "洗衣机", "电视机", "冰 箱", "空调机" }; // 定义数组是干什么用的
// 声明double类型的数组:price,并初始化。
double[] price = new double[] { 124.23, 4500, 8800.90, 5000.88, 4456,
12000.46 };
// 声明返回值类型为:boolean的login()方法
public boolean login()
{
// 声明变量flag,类型为boolean,初始值为:false,作为是否登录成功的标志
boolean flag = false;
// 键盘输入
Scanner input = new Scanner(System.in);
// 打印
System.out.print("请输入用户名: ");
// 声明变量name,接收输入用户名
String name = input.next();
// 打印
System.out.print("请输入密码: ");
// 声明变量pwd,接收输入密码
String pwd = input.next();
// if判断用户名和密码是否正确
if (name.equals("TOM") && pwd.equals("123"))
{
// 打印
System.out.println("登录成功! ");
// 修改是否登录成功的标志
flag = true;
}
// else情况
else
{
// 打印
System.out.println("用户名或密码不匹配,登录失败!");
}
// 返回是否登录成功的标志:成功(true),失败(false)
return flag;// 这段代码为什么要加返回值
}
// 声明返回值为StringBuffer类型的方法change(double d),参数为double类型的d
public StringBuffer change(double d)// 这是什么意思啊
{
// StringBuffer str:声明StringBuffer类型的变量str
// String.valueOf(d):获取d的字符串值
// new StringBuffer(String.valueOf(d)):实例化str,调用了StringBuffer的构造方法
StringBuffer str = new StringBuffer(String.valueOf(d));// 这一句
// str.indexOf("."):返回第一个.所在位置:如果该值返回大于等于4,则进入for循环,否则跳过
for (int i = str.indexOf(".") - 3; i > 0; i = i - 3)
{// 这一句
// 在i出添加,如8,800.9
str.insert(i, ',');// 还有这一句
}
// 返回StringBuffer类型的字符串
return str;
}
// 声明返回值为void的方法showGoods()
public void showGoods()
{
// 打印
System.out.print("*********欢迎进入商品批发城*********");
// 打印
System.out.print("\n\t编号\t商品\t价格\n");
// for循环输出商品:goods.length用到开始声明的goods来获取数组长度
for (int i = 0; i < goods.length; i++)
{
// 打印:因为数组从0开始,而商品只能从1开始,所以i+1。\t制表符
System.out.print("\t" + (i + 1));
// 打印第i个商品
System.out.print("\t" + goods[i]);
// 打印第i个商品的价格。\n回车
System.out.print("\t" + change(price[i]) + "\n");
}
// 打印
System.out.println("**********************************");
}
// 主方法
public static void main(String[] args)
{
// 键盘输入
Scanner input = new Scanner(System.in);
// 声明Goods类的对象g,并实例化
Goods g = new Goods();
// 声明int变量serial, num
int serial, num;
// 声明double变量total
double total = 0;
// 判断是否登录成功
if (g.login())
{
// 打印商品信息
g.showGoods();
// 输入商品编号
System.out.print("请输入您批发的商品编号:");
// 接收
serial = input.nextInt();
// 输入批发数量
System.out.print("请输入批发数量:");
// 接收
num = input.nextInt();
// 计算总金额:price数组是从0开始的,商品数量是从1开始,第一个商品对应第0个价格
total = g.price[serial - 1] * num;// 计算总金额 //这一句
// 打印总金额
System.out.print("您需要付款:" + g.change(total));
}
}
}

❻ Java100行以上源代码,至少五个class以及一个interface,可以简单点

下面是一个可能的Java源代码,它包含了一个接口租冲薯(Shape)和五个类(Circle, Rectangle, Triangle, Square 和 Main)。它的功能是计算不同形状的面积和周长。
//定义一个接口Shape,有两判指个抽象方法:getArea()和getPerimeter()interface Shape { double getArea(); double getPerimeter();
}//定义一个类Circle,实现Shape接口class Circle implements Shape { //定义一个私有属性radius,表示圆的半径
private double radius; //定义一个公有构造方法,用于初始化radius
public Circle(double radius) { this.radius = radius;
} //实现getArea()方法,返回圆的面积
public double getArea() { return Math.PI * radius * radius;
} //实现getPerimeter()方法,返回圆的周长
public double getPerimeter() { return Math.PI * radius * 2;
}
}//定义一个类Rectangle,实现Shape接口class Rectangle implements Shape { //定义两个私有属性width和height,表示矩形的宽度和高度
private double width; private double height; //定义一个公有构造方法,用于初始化width和height
public Rectangle(double width, double height) { this.width = width; this.height = height;
} //实现getArea()方法,返回矩形的面积
public double getArea() { return width * height;
} //实现getPerimeter()方法,返回矩形的周长
public double getPerimeter() { return (width + height) *2;
}
}//定义一个类Triangle,实现Shape接口class Triangle implements Shape { //定义三个私有属性a,b,c表示三角形的三条边长
private double a; private double b; private double c; //定义一个公有构造方法,用于初始化a,b,c,并检查是否满足三角形条件(任意两边之和大于第三边)
public Triangle(double a, double b, double c) throws Exception{ if (a + b > c && a + c > b && b + c > a) {
this.a = a; this.b = b;
this.c = c;
} else {
throw new Exception("Invalid triangle");
}
} //实现getArea()方法,返回三角形的面积(使用海伦公式)
public double getArea() { //计算半周长p
double p = (a + b + c) /2; //计算并返回面积s(使用Math.sqrt()函数求平方根)
return Math.sqrt(p * (p - a) * (p - b) * (p - c));
} //实现getPerimeter()方法,返回三角形的周长
public double getPerimeter(){ return a + b + c;
}
}//定义一个类Square,继承Rectangle类,并重写构造方法和toString()方法class Square extends Rectangle { //重写构造方法,在调用父类构造方法时传入相弊者同的参数side作为width和height
public Square(double side){ super(side, side);
} //重写toString()方法,在原来基础上加上"Square:"前缀,并只显示side属性而不显示width和height属性(使用String.format()函数格式化字符串)
@Override
public String toString(){ return String.format("Square: side=%.2f", super.width); /* 或者直接使用super.getPerimeter()/4作为side */
/* return String.format("Square: side=%.2f", super.getPerimeter()/4); */

/* 注意:不能直接访问super.side属性,

❼ 求一个简单又经典的JAVA数据库连接的例子,要有源代码哦!

我就弄的用户登入的代码吧.这个挺简单的.
这是题目:
用户登陆验证:
1.创建数据库Test,并新建用户表users
字段包含:username varchar(20) not null
userpwd varchar(20) not null

在JBUILDER中编写Long类,实现登陆界面,并在用户输入用户名和密码后,
完成按纽的单击事件,对用户输入的数据进行验证,
(需要严整数据是否为空,密码长度必须是15位),
并实现与数据库的连接,将用户输入的用户名密码与表中的记录比较,
若用户名正确且密码正确,弹出提示框告知登陆成功,否则登陆失败。

这是代码:
//连接数据库
boolean isLogin(String name,String pwd){
boolean flag=false;
Connection conn=null;
PreparedStatement pst=null;
ResultSet rs=null;
//加载驱动
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
} catch (ClassNotFoundException ex) {
ex.printStackTrace();
}
//连接数据库
try {
conn=DriverManager.getConnection("jdbc:odbc:login");
String sql="select * from [user] where username=? and userpwd=?";
pst=conn.prepareStatement(sql);
pst.setString(1,name);
pst.setString(2,pwd);
rs=pst.executeQuery();
if(rs.next())
flag=true;
} catch (Exception ex) {
ex.printStackTrace();
}finally{
try {
conn.close();
} catch (Exception ex) {
ex.printStackTrace();
}
}
return flag;

}
//验证方法
public void jButton1_actionPerformed(ActionEvent e) {
String name=jTextField1.getText();
String pwd=jTextField2.getText();
//错误处理
if(name.equals("")||pwd.equals(""))
JOptionPane.showMessageDialog(this,"请输入完整的信息");
else {
if(isLogin(name,pwd))
JOptionPane.showMessageDialog(this,"登陆成功");
else
JOptionPane.showMessageDialog(this,"用户名或密码错误");

}

}
}
.....
.....
这是在事件里写的,

阅读全文

与java案例源代码相关的资料

热点内容
php生成js文件 浏览:285
云端服务器什么作用 浏览:1
关闭系统运行命令 浏览:956
程序员哪找兼职 浏览:785
什么app可以让孩子学习数学 浏览:202
怎么弄坏空调的压缩机 浏览:983
phpexcel浮点数 浏览:484
怎么用命令方块让村民帮自己战斗 浏览:571
java随机数代码 浏览:828
主题叫火什么的app 浏览:880
智能水表加密阀门 浏览:653
月饼玩具解压 浏览:510
迅捷pdf编辑器官网 浏览:962
打造云服务器的应用 浏览:613
程序员去医院做项目 浏览:332
viper4android安卓60 浏览:493
java软件源码 浏览:162
空气压缩机的类型 浏览:355
centos图形命令行界面切换 浏览:240
新京报新闻APP什么时候有的 浏览:818