控制台打印出一个99乘法表
public static void main(String[] args) {
for(int i = 1;i<10;i++) {
for(int j = 1;j<=i;j++) {
int number = i*j;
System.out.print(i+" "+"X"+" "+j+"="+" "+number+" ");
}
System.out.print("\n");
}
}
1 X 1= 1
2 X 1= 2 2 X 2= 4
3 X 1= 3 3 X 2= 6 3 X 3= 9
4 X 1= 4 4 X 2= 8 4 X 3= 12 4 X 4= 16
5 X 1= 5 5 X 2= 10 5 X 3= 15 5 X 4= 20 5 X 5= 25
6 X 1= 6 6 X 2= 12 6 X 3= 18 6 X 4= 24 6 X 5= 30 6 X 6= 36
7 X 1= 7 7 X 2= 14 7 X 3= 21 7 X 4= 28 7 X 5= 35 7 X 6= 42 7 X 7= 49
8 X 1= 8 8 X 2= 16 8 X 3= 24 8 X 4= 32 8 X 5= 40 8 X 6= 48 8 X 7= 56 8 X 8= 64
9 X 1= 9 9 X 2= 18 9 X 3= 27 9 X 4= 36 9 X 5= 45 9 X 6= 54 9 X 7= 63 9 X 8= 72 9 X 9= 81
将一个数组内容倒序输出
public static void main(String[] args) {
String[] array ={"aa","bb","cc","dd","ee","ff"};
reverses(array);
System.out.println(Arrays.toString(array));
Integer[] array1= {11,22,33,44,55,66};
reverses(array1);
System.out.println(Arrays.toString(array1));
}
private static<T> void reverses(T[] array) {
for(int i=0;i<array.length/2;i++) {
T temp=array[i];
array[i]=array[array.length-i-1];
array[array.length-i-1]=temp;
}
}
对泛型的理解
public static void main( String args[] ){
Integer[] intArray = { 33, 46,77, 9, 0};
Double[] doubleArray = { 66.6, 77.7, 88.8,};
String[] stringArray = { "hello,myjava", "java", "I","will","conquer","you"};
Character[] charArray = { '', '', '', '' };
Long[] longArray = {55555555l,777777777l,6666666666666666669l};
printArray( intArray);
printArray( doubleArray );
printArray( stringArray );
printArray( charArray );
printArray( longArray );
}
public static < T > void printArray( T[] anyArray ){
for ( T anynumber : anyArray ){
System.out.println(anynumber);
}
}
map嵌套
public static void main(String[] args) {
HashMap<String, HashMap<String, News>> hamp = new HashMap<String, HashMap<String, News>>();
HashMap<String, News> map = new HashMap<String, News>();
map.put("第一版",new News("www.520.com","测试","琪得龙"));
map.put("第二版", new News("www.qq.com","测试","奔波儿灞"));
hamp.put("娱乐类", map);
HashMap<String, News> map1 = new HashMap<String, News>();
map1.put("第三版",new News("www.weixinmap.com","测试","不吃老鼠的猫"));
map1.put("第四版", new News("www.baidunews.com","测试","卖火柴的小女孩"));
hamp.put("社会类", map1);
HashMap<String, News> map2 = new HashMap<String, News>();
map2.put("第六版",new News("www.baidunews.com","测试","发重力超人"));
map2.put("第七版",new News("www.baidunews.com","测试","西北伽利略"));
hamp.put("民生类", map2);
Set<String> leixingset =hamp.keySet();
for (String leixing : leixingset) {
HashMap<String, News> zong =hamp.get(leixing);
Set<String> jutinews =zong.keySet();
for (String newnew : jutinews) {
System.out.println(newnew+" "+zong.get(newnew));
}
}
}
判断一个文件并移动它
public static void main(String[] args) {
PracOne pra=new PracOne();
File file =new File("E:\\HelloWorld.txt");
if(file.exists()) {
System.out.println("是文件");
}else {
System.out.println("不是文件");
}
if(file.isDirectory()) {
System.out.println("是目录");
}
file.renameTo(new File("E:\\IoTest\\HelloWorld.txt"));
System.out.println("移动成功");
}
向一个文件写内容
public static void main(String[] args) {
File file =new File("E:\\Hello.txt");
try {
FileOutputStream op =new FileOutputStream(file);
String str ="HelloJavaWorld你好世界";
byte[] be=str.getBytes();
if(!(file.exists())) {
try {
file.createNewFile();
op.write(be, 0, be.length);
System.out.println("输出成功");
} catch (IOException e) {
e.printStackTrace();
}
}else {
try {
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
try {
op.write(be, 0, be.length);
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("输出成功");
}
} catch (Exception e) {
e.printStackTrace();
}
}
从磁盘读取一个文件到内存中,再打印到控制台
public static void main(String[] args) {
File file = new File("E:\\pra\\wuqi.txt");
try {
FileInputStream fis = new FileInputStream(file);
int len = 0;
byte[] buf = new byte[1024];
StringBuffer sb = new StringBuffer();
while ((len = fis.read(buf)) != -1) {
sb.append(new String(buf, 0, len));
}
System.out.println(sb);
fis.close();
} catch (Exception e) {
e.printStackTrace();
}
}
使用字节流读取文件,并统计某个字符出现的次数
public static void main(String[] args) {
File file =new File("E:\\calcCharNum.txt");
FileInputStream is =null;
try {
is= new FileInputStream(file);
//定义一个变量接收文件的值
int da;
try {
int Acount=0;
int acount=0;
while((da=is.read())!=-1) {
char shu=(char)da;
if(shu=='A') {
Acount++;
}
if(shu=='a') {
acount++;
}
}
System.out.println("A的数量是:"+Acount+" "+" a的数量是"+acount);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
一个四位数,每位数相加之和的和大于25的概率是多少
public static void main(String[] args) {
/*int型的话不好转double(如果比值都为int)
* 考虑到最后用到的概率值因此用double型
*num1:出现符合条件的次数
*/
double num1 = 0.0;
int num5 = 0;
//循环10000次,相当于统计出一万个随机的四位数字
for (int i = 0; i < 10000; i++) {
//给出一个四位数的随机数
int num =(int)(Math.random()*10000);
//取出每位数用余10求得
int gewei =num%10;
int shiwei =num/10%10;
int baiwei =num/100%10;
int qianwei =num/1000%10;
//四位数相加后的和
int total = gewei+shiwei+baiwei+qianwei;
//如果这个数看做一个有千位数的话千位上不为0
if(total>25 && qianwei != 0) {
//每大一次25统计一次
num1++;
}else {
num5++;
}
}
System.out.println("大于25的次数"+num1);
System.out.println("小于25的次数"+num5);
//概率:出现符合条件的次数比总次数
double rate =num1/10000;
System.out.println("每位数和的大于25的概率是多少"+rate);
}
对输入的账号密码做有效性验证,可有三次试错机会
public static void main(String[] args) {
String username = "admin";
String password = "618121";
for(int x=0; x<3; x++) {
Scanner sc = new Scanner(System.in);
System.out.println("请输入用户名:");
String name = sc.nextLine();
System.out.println("请输入密码:");
String pwd = sc.nextLine();
if(username.equals(name) && password.equals(pwd)) {
System.out.println("登录成功");
break;
}else {
if((2-x) ==0) {
System.out.println("用户名和密码被锁定,请与管理员联系");
}else {
System.out.println("登录失败,你还有"+(2-x)+"次机会")
}
}
}
}
将一个符号替换
public static void main(String[] args) {
StringBuilder str = new StringBuilder("129.168.1.129");
for (int i = 0; i < str.length(); i++) {
char in = str.charAt(i);
if (in =='.') {
str.setCharAt(i, '*');
}
}
System.out.println("替换后的"+str);
}
统计某个字符出现的次数
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("请输入一个字符串数据:");
String s = sc.nextLine();
int bigCount = 0;
int smallCount = 0;
int numberCount = 0;
int blankCount = 0;
int anotherCount = 0;
for(int x=0; x<s.length(); x++) {
char ch = s.charAt(x);
if(ch>='A' && ch<='Z') {
bigCount++;
}else if(ch>='a' && ch<='z') {
smallCount++;
}else if(ch>='0' && ch<='9') {
numberCount++;
}else if(' '==s.charAt(x)) {
blankCount++;
}else {
anotherCount++;
}
}
System.out.println("大写字符:"+bigCount+"个");
System.out.println("小写字符:"+smallCount+"个");
System.out.println("数字字符:"+numberCount+"个");
System.out.println("空格字符"+blankCount+"个");
System.out.println("其他字符"+anotherCount+"个");
}
判断是否是邮箱格式
public static void main(String[] args) {
System.out.println("开始输入判断.java的程序");
Scanner in = new Scanner(System.in);
String input=in.nextLine();
int index1 = input.indexOf(".");
if(input.substring(index1,input.length() ).contentEquals(".java")) {
System.out.println("是.java结束的文件");
}else {
System.out.println("不是.java文件");
}
//开始判断邮箱的具体位置
System.out.println("开始输入判断邮箱的程序");
Scanner in1 = new Scanner(System.in);
//接收到字符串型数据
String input1=in1.nextLine();
//输入的字符某个位置
int index2 = input1.indexOf("@");
//获取字符串中制定位置的字符
char zifu = input1.charAt(index2);
int index3 = input1.indexOf(".");
//获取字符串中制定位置的字符
char zifu1 = input1.charAt(index3);
//substring括号里的的起始从符号 '.' 就开始算起
if(zifu =='@' && input1.substring(index3, input1.length()).equals(".com")) {
System.out.println("是正确的邮箱");
}else {
System.out.println("不是正确的邮箱");
System.out.println(input1.substring(index1, input.length()).contentEquals(".com"));
System.out.println(zifu =='@');
}
}
注册账户信息
public String cardNumber;
public String costType;
public double telephoneFee;
public String userName;
public String password;
public void registed() {
System.out.println("************选择卡号************");
String[] array=new String[9];
int count = 0;
while(true) {
int num =(int) (Math.random()*100000000);
String str ="139"+num;
array[count] = str;
if(array[count] != null) {
count++;
}
if(count == 9) {
break;
}
}
for (int i = 1; i <= 3; i++) {
for (int j = 1; j <= 3; j++) {
System.out.print(" "+array[i*j-1]);
}
System.out.println();
}
System.out.println("开始注册");
Scanner sc = new Scanner(System.in);
System.out.println("请输入手机号:");
String inputNum = sc.nextLine();
//此处得确保输入的数是随机生成的数之一
for (int n = 0; n < 9; n++) {
//如果输入的是随机生成的号码之一,才能注册
if(inputNum.equals(array[n])) {
System.out.println("请输入用户名:");
Scanner scu = new Scanner(System.in);
String userName = scu.nextLine();
//如果该用户名没被注册,则可以用该名字注册
if (!(userName.equals("琪得龙东强"))) {
Scanner scp = new Scanner(System.in);
System.out.println("请确保密码长度不小于8位且包含数字与字母,区分大小写");
System.out.println("请输入密码:");
String password = scp.nextLine();
//密码中需包含数字与字母等信息,且长度也有要求;
int bigCount = 0;
int smallCount = 0;
int numberCount = 0;
int total = 0;
for(int x=0; x<password.length(); x++) {
char ch = password.charAt(x);
if(ch>='A' && ch<='Z') {
bigCount++;
}else if(ch>='a' && ch<='z') {
smallCount++;
}else if(ch>='0' && ch<='9') {
numberCount++;
}
}
total=bigCount+smallCount;
if (password.length()>8 && total>0 && numberCount>0) {
System.out.println("密码安全性高");
for (int i = 0; i < 100; i++) {
if (userName.equals(userName) && password.equals(password)) {
System.out.println("请再次输入您的用户名:");
Scanner scau = new Scanner(System.in);
String userName1 = scau.nextLine();
System.out.println("请再次输入密码:");
Scanner scap = new Scanner(System.in);
String password1 = scap.nextLine();
if (userName1.equals(userName) && password1.equals(password)) {
System.out.println("注册成功");
this.cardNumber=inputNum;
this.userName=userName1;
this.password=password1;
SuperMan su=new SuperMan();
this.costType=su.description();
Method me=new Method();
double fundamentalPhoneFee=0;
this.telephoneFee=me.givePhoneValue(50,fundamentalPhoneFee);
break;
}else {
System.out.println("请您输入与上次同一个账号与密码");
continue;
}
}
}
}else {
System.out.println("密码安全性较低,建议您重新设置");
}
}else {
System.out.println("系统中已经存在此名字");
}
}else {
continue;
}
}
}
通过JDBC向数据库插入数据
public static void insertCardInformation() {
// 加载驱动
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
Connection conn = null;
PreparedStatement p = null;
//与数据库建立连接
try {
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/userStorage?useUnicode=true&characterEncoding = utf-8", "root", "root");
InsertUserInfo in=new InsertUserInfo();
in.registed();
String sql = "insert into storage values(?,?,?,?,?)";
//发生SQL语句
p=conn.prepareStatement(sql);
//插入数据,设置每个输入参数的值
p.setString(1, in.cardNumber);
p.setString(2, in.costType);
p.setDouble(3, in.telephoneFee);
p.setString(4, in.userName);
p.setString(5, in.password);
//得到返回结果
p.executeUpdate();//表示执行PreparedStatement 中封装的sql语句
} catch (SQLException e) {
System.out.println("PreparedStatement 对象创建失败 。。。。");
e.printStackTrace();
}finally {
// 释放资源
if(p != null){
try {
p.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(conn != null){
try{
conn.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
从数据库拿数据做登陆验证
public static void getCardInformation(String cardno,String password) {
List<Card> list = new ArrayList<>();
// 加载驱动
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Connection conn = null;
PreparedStatement stmt = null;
ResultSet rs =null;
// 获得链接
try {
conn = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/userStorage?useUnicode=true&characterEncoding = utf-8", "root", "root");
// 执行sql条件查询语句
String sql="select * from storage where cardNo=? and userPwd =?";
stmt = conn.prepareStatement(sql);
stmt.setString(1, cardno);
stmt.setString(2, password);
//负责保存prepareStatement执行后产生的结果
rs = stmt.executeQuery();
Card ca =null;
//便利数据,处理返回结果
if(rs.next()) {
ca = new Card();
ca.setCardNumber(rs.getString("cardNo"));
ca.setCostType(rs.getString("type"));
ca.setTelephoneFee(rs.getDouble("phoneFee"));
ca.setUserName(rs.getString("userName"));
ca.setPassword(rs.getString("userPwd"));
list.add(ca);
System.out.println("登陆成功");
}else {
System.out.println("登陆失败");
}
for (Card card : list) {
System.out.println(card);
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally {// 释放资源
if(rs != null){
try {
rs.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(stmt != null){
try {
stmt.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(conn != null){
try {
conn.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
饿汉模式
HungrySingleton() {
}
private static HungrySingleton instance=new HungrySingleton();
public static HungrySingleton getInstance() {
return instance;
}
跑步接力赛
public class Copy implements Runnable {
//每个人跑的时候显示的数量
private int num = 10;
private int total = 1000;
//记数
private int count = 0;
private boolean boo = false;
public synchronized void run() {
//运行接力赛这个经过线程同步的方法
while (!boo) {
//如果跑满1000,就告知已经跑满1000米
if (total == 0) {
System.out.println("已经跑满1000米");
boo = true;
break;
}
//运行接力的方法
relay();
total-=100;
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
//一个线程跑完要return掉
return;
}
}
public synchronized void relay(){
//如果没跑完就继续跑
if (total>0){
String thread = Thread.currentThread().getName();
//按提示输出
System.out.println(thread + "拿到了接力棒");
//设定单个选手的跑的变量
for (int i = 1; i <= num; i++) {
System.out.println(Thread.currentThread().getName() + "跑了" + (i * 10) + "米");
count += 10;
}
}
}
}
//调用
public static void main(String[] args) {
Copy rc=new Copy();
//启动线程,四位选手分别跑
new Thread(rc,"1号选手").start();
new Thread(rc,"2号选手").start();
new Thread(rc,"3号选手").start();
new Thread(rc,"4号选手").start();
}
1号选手拿到了接力棒
1号选手跑了10米
1号选手跑了20米
1号选手跑了30米
1号选手跑了40米
1号选手跑了50米
1号选手跑了60米
1号选手跑了70米
1号选手跑了80米
1号选手跑了90米
1号选手跑了100米
4号选手拿到了接力棒
4号选手跑了10米
4号选手跑了20米
4号选手跑了30米
4号选手跑了40米
4号选手跑了50米
4号选手跑了60米
4号选手跑了70米
4号选手跑了80米
4号选手跑了90米
4号选手跑了100米
3号选手拿到了接力棒
3号选手跑了10米
3号选手跑了20米
3号选手跑了30米
3号选手跑了40米
3号选手跑了50米
3号选手跑了60米
3号选手跑了70米
3号选手跑了80米
3号选手跑了90米
3号选手跑了100米
2号选手拿到了接力棒
2号选手跑了10米
2号选手跑了20米
2号选手跑了30米
2号选手跑了40米
2号选手跑了50米
2号选手跑了60米
2号选手跑了70米
2号选手跑了80米
2号选手跑了90米
2号选手跑了100米
向数组中随机插入一个数保证这个数处于数组中的合适位置,插入的过程中排序,(下面写这种方法并不是最优的方法)
public static void main(String[] args) {
//初始数组,
int[] numArray1={10,33,76,19,66,4};
//为保证这个数组的最后一位为空,给一个比他大一个长度的空间;
int[] numArray = new int[numArray1.length+1];
for (int i = 0; i < numArray1.length; i++) {
//传值
numArray[i]=numArray1[i];
}
//比插入的值小的次数,也就以此判断要插入的位置;
int index=0;
System.out.println("请插入一个要比较的整数");
Scanner input =new Scanner(System.in);
int num=input.nextInt();
//分别用两个数组来存储比输入的数大的或小的数;
int[] min=new int[numArray.length];
int[] max=new int[numArray.length];
//数组中空的位置默认数字是0,因此不能参与到排序中去否则影响排序结果;
for (int i = 0; i < numArray.length-1; i++) {
//比输入的数小的放入min数组中;
if(num >= numArray[i]) {
min[i]=numArray[i];
index++;
continue;
}
else {
max[i]=numArray[i];
}
}
//对两个数组升序排列;
Arrays.sort(min);
Arrays.sort(max);
//根据比较的结果放入合适的位置
numArray[index]=num;
for (int i = 0; i < index; i++) {
//排序结果大致是0,0,0,数,数。因此要把这个数从第一个索引出开始
min[i]=min[i+numArray.length-index];
numArray[i]=min[i];
}
for (int i = index+1; i < numArray.length; i++) {
numArray[i]=max[i];
}
//将两个数组拼接起来遍历就是排序好的数组;
System.out.println("排序后的数组为");
for (int i : numArray) {
System.out.print(" "+i);
}
}
//运行结果
请插入一个要比较的整数
777
排序后的数组为
4 10 19 33 66 76 777
把一个文件内容拷贝到另一个文件中
public static void main(String[] args) {
FileInputStream qu = null;
FileOutputStream cunFile = null;
try {
qu = new FileInputStream("E:\\hello.txt");
cunFile = new FileOutputStream("E:\\newpic\\wuqi.txt");
int temp;
while ( (temp = qu.read()) != -1) {
cunFile.write(temp);
}
System.out.println("写入成功");
}catch (IOException ioe) {
ioe.printStackTrace();
}finally{
try {
if(qu!=null)
qu.close();
if(cunFile!=null)
cunFile.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
二叉树的前序遍历方法
public class TreeNode {
private char value;
TreeNode lNode;
TreeNode rNode;
public int getValue() {
return value;
}
public void setValue(char value) {
this.value = value;
}
public TreeNode getlNode() {
return lNode;
}
public void setlNode(TreeNode lNode) {
this.lNode = lNode;
}
public TreeNode getrNode() {
return rNode;
}
public void setrNode(TreeNode rNode) {
this.rNode = rNode;
}
public TreeNode(char value) {
this.value = value;
}
public void printShow() {
System.out.println(value);
if (lNode != null) {
lNode.printShow();
}
if (rNode != null) {
rNode.printShow();
}
}
}
public class Tree {
TreeNode root;
public TreeNode getRoot() {
return root;
}
public void setRoot(TreeNode root) {
this.root = root;
}
public Tree() {
}
public void printShow() {
if(root!=null){
root.printShow();
}
}
}
public class TestTree {
public static void main(String[] args) {
Tree Tr = new Tree();
TreeNode root = new TreeNode('a');
Tr.setRoot(root);
TreeNode lNode = new TreeNode('b');
TreeNode rNode = new TreeNode('c');
root.setlNode(lNode);
root.setrNode(rNode);
lNode.setlNode(new TreeNode('d'));
rNode.setrNode(new TreeNode('f'));
lNode.setlNode(new TreeNode('e'));
System.out.println("前序遍历方法");
Tr.printShow();
}
}
冒泡
public static void main(String[] args) {
int[] array= {5,4,77,89,43};
for (int i = 0; i < array.length; i++) {
for (int j = 0; j < array.length-i-1; j++) {
if (array[j]>array[j+1]) {
int min=array[j+1];
array[j+1]=array[j];
array[j]=min;
}
}
}
for (int i : array) {
System.out.println(i);
}
}
TCP
public class TcpClint {
public static void main(String[] args) throws IOException, ClassNotFoundException {
Socket socket =new Socket("127.0.0.1",5000);
ObjectOutputStream objo=new ObjectOutputStream(socket.getOutputStream());
objo.writeObject("我是客户端");
ObjectInputStream obji=new ObjectInputStream(socket.getInputStream());
Object obj=obji.readObject();
socket.close();
}
}
ublic class TcpSever {
public static void main(String[] args) {
try {
ServerSocket serverSocket =new ServerSocket(5000);
while (true) {
//等待客户端连接
Socket accept=serverSocket.accept();
System.out.println("客户端IP:"+accept.getInetAddress()+" 端口为:"+accept.getPort()+"连接成功");
ObjectInputStream obji=new ObjectInputStream(accept.getInputStream());
try {
Object obj=obji.readObject();
System.out.println("sever获取数据为:"+obj);
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
ObjectOutputStream objo=new ObjectOutputStream(accept.getOutputStream());
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}