Java - 常用类

版权声明:call me 刘英雄 https://blog.csdn.net/weixin_42526141/article/details/82848464

常用类:顾名思义,就是在Java中常用的类,是jdk给我们提供的,封装了很多的方法,供我们方便使用,常用类主要有以下几个:

包装类:JDK为每一种基本数据类型都提供一个对应的包装类。

byte --> java.lang.Byte

short --> java.lang.Short

int -->java.lang.Integer

long -->java.lang.Long

char -->java.lang.Character

float -->java.lang.Float

double -->java.lang.Double

boolean -->java.lang.Boolean

Math类:Math是java给我们提供的操作数学的类,提供了很多静态方法,如max、min等

String:操作字符串的常用类,String类是final类,也即意味着String类不能被继承,并且它的成员方法都默认为final方法。在Java中,被final修饰的类是不允许被继承的,并且该类中的成员方法都默认为final方法。

StringBuffered

StringBuffer的内部实现方式和String不同,StringBuffer类属于一种辅助类,可预先分配指定长度的内存块建立一个字符串缓冲区,StringBuffer在进行字符串处理时,使用StringBuffer类的append方法追加字符,不生成新的对象,在内存使用上要优于String类。所以在实际使用时,如果经常需要对一个字符串进行修改,例如插入、删除等操作,使用StringBuffer要更加适合一些

注意:

1.String对象一旦被创建就是固定不变的了,对String对象的任何改变都不影响到原对象,相关的任何change操作都会生成新的对象

2.String使用 “+” 进行字符串拼接时,字符串对象都需要寻找一个新的内存空间来容纳更大的字符串,这无疑是一个非常消耗时间的操作。

package com.liudm.demo10;

public class Test {
	public static void main(String[] args) {
		//包装类
		int n1 = 5;
		Integer n2 = n1;
		int n3 = Integer.parseInt("12");
		double d = Double.parseDouble("12.5");
		Float.parseFloat("42.5");
		System.out.println(n3);
		
		//数学类
		System.out.println(Math.E);    //常数
		System.out.println(Math.PI);
		System.out.println(Math.abs(-4));  //求绝对值
		System.out.println(Math.floor(4.9));   //向下取整
		System.out.println(Math.round(3.6));   //四舍五入
		System.out.println(Math.max(4, 7));
		System.out.println(Math.min(4, 7));
		System.out.println(Math.sqrt(4));  //开平方
		System.out.println(Math.random());  //生成0.0到1.0之间的随机数
		System.out.println((int)(Math.random()));   //把随机数强制转换为int整型,结果全为0
		System.out.println((int)(Math.random()*10));  //得到0到9之间的整型随机数
		System.out.println((int)(Math.random()*10 + 10));  //得到10到19之间的整型随机数
	}
}
package com.liudm.demo10;

import java.util.Random;

public class Test1 {
	public static void main(String[] args) {
		Random random = new Random();
		for (int i = 0; i < 6; i++) {
			int n = random.nextInt(10);   //控制范围0~9
			//int n = random.nextInt(100);   //控制范围0~99
			//int n = random.nextInt(10) + 90;   //控制范围90~99
			System.out.print( n + "  ");
		}
		System.out.println();
		
		//两次生成的随机数保持一致
		Random random1 = new Random(2);  //种子值
		for (int i = 0; i < 6; i++) {
			int n = random1.nextInt(10);   //控制范围0~9
			System.out.print( n + "  ");
		}
		System.out.println();
		Random random2 = new Random(2);  //种子值
		for (int i = 0; i < 6; i++) {
			int n = random2.nextInt(10);   //控制范围0~9
			System.out.print( n + "  ");
		}
		
	}
}
package com.liudm.demo10;

import java.util.Scanner;

public class Test2 {
	public static void main(String[] args) {
		//字符串String类
		//验证用户名和密码
		Scanner sc = new Scanner(System.in);
		System.out.println("请输入用户名:");
		String username = sc.next();
		//用户名:长度4~8
		System.out.println(username.length());  //数组:lenth
		if(username.length() >= 4 && username.length() <= 8){
			System.out.println("用户名合法,请继续下一步...");
			System.out.println("请输入密码:");
			String password = sc.next();
			if (password.length() >= 6 && password.length() <= 10) {
				System.out.println("密码合法,请再次输入密码:");
				String repassword = sc.next();
				if (password.equals(repassword)) {
				//if (password.contentEquals(repassword))   //忽略大小写
					System.out.println("两次密码一致");
				} else {
					System.out.println("两次密码不一致,请重新输入");
				}
			}
		}
	}
}
package com.liudm.demo10;

public class Test3 {
	public static void main(String[] args) {
		String s = " Hello hello world ";
		System.out.println(s.length());
		System.out.println(s.startsWith("h"));
		System.out.println(s.endsWith("ld"));
		System.out.println(s.substring(1, 4));  //字符串截取,包头不包尾
		System.out.println(s.substring(4));   //字符串截取,从指定字符到结束
		System.out.println(s.charAt(3));  //使用不当会产生数组下标异常
		System.out.println(s.charAt(14));
		System.out.println(s.indexOf('e'));  //返回字符下标,从前往后找
		System.out.println(s.lastIndexOf('e'));   //返回字符下标,从后往前找
		System.out.println(s.replace('e', 'a'));   //替换
		System.out.println(s.trim().length());   //首尾空格
		
		String [] ss = s.split(" ");  //以空格为界拆分
		for (int i = 0; i < ss.length; i++) {
			System.out.println(ss[i]);
		}
	}
}

 

package com.liudm.demo10;

public class Test5 {
	public static void main(String[] args) {
		String s = "hello";
		String s1 = s + "aa";
		String s2 = s1 + "bb";
		System.out.println(s2);
		
		//StringBuffer,String的增强版,效率高于String
		StringBuffer sb = new StringBuffer();
		//StringBuffer sb1 = new StringBuffer("helloworld");  //赋初始值
		sb.append("hello").append("aaa").append("bbb");  //append:追加
		System.out.println(sb);
		System.out.println(sb.toString());
		//sb.delete(start,end);
		sb.delete(0,3);
		System.out.println(sb);
		
		System.out.println(sb.reverse());  //转制
		
		String price = "4863148953279";
		StringBuffer sbPrice = new StringBuffer(price);  //
//		sbPrice.insert(3, ',');
//		System.out.println(sbPrice);   //输出 486,3148953279
		for (int i = sbPrice.length(); i > 0; i -= 3) {  //i -= 3   ---》i = i - 3
			sbPrice.insert(i, ',');  //插入
		}
        sbPrice.delete(sbPrice.length()-1, sbPrice.length());   //删除最后一个逗号
		System.out.println(sbPrice);
	}
}

 

package com.liudm.demo10;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class Test6 {
	public static void main(String[] args) throws ParseException {
		//将日期转换为字符串
		Date date = new Date();
		System.out.println(date);
		SimpleDateFormat simple = new SimpleDateFormat("yyyy-mm-dd HH:MM:ss");
		String sdate = simple.format(date);
		System.out.println(sdate);
		
		//将字符串转换为日期
		String str = "2018-05-25 19:01:43";
		Date d = simple.parse(str);  //有异常,添加throw ParseException
		//异常:运行时异常、编译时异常(首检异常)
		System.out.println(d);
	}
}

 


package com.liudm.demo10;

import java.util.Calendar;

public class Test7 {
	public static void main(String[] args) {
		Calendar cal = Calendar.getInstance();  //获得实例
		System.out.println(cal.get(Calendar.YEAR));
		
		System.out.println(cal.get(Calendar.MONTH)+1);
		//System.out.println(cal.get(Calendar.MONTH));  //国外习惯
		
		System.out.println(cal.get(Calendar.DAY_OF_MONTH));
		
		System.out.println(cal.get(Calendar.DAY_OF_WEEK)-1);
		//System.out.println(cal.get(Calendar.DAY_OF_WEEK));  //国外习惯
		
		System.out.println(cal.get(Calendar.HOUR));
		
		cal.set(Calendar.YEAR, 2012);
	}
}

 

练习:判断.java文件名是否正确,判断邮箱格式是否正确。

合法的文件名应该以.java结尾

合法的邮箱名中至少要包含“@”和“.”, 并检查“@”是否在“.”之前

package com.liudm.demo10;

Test4


实验:要求:编码实现双色球功能

  • 双色球规则红球33选6,蓝球16选1,不允许重复
  • 使用Math类的random()方法在1到33内随机产生6个红球号码,每产生一个判断是否已经在数组中存在,不存在则保存于数组,否则重选
  • 从1到16间随机产生一个蓝球号码

最后输出双色球号数。

package shuangseqiu;

import java.util.Random;

import org.omg.CORBA.PUBLIC_MEMBER;

public class Test {
	public static void main(String[] args) {
		int [] redNum = new int[6];
		int number = 0;
		Random random = new Random();
		for (int i = 0; i < 6; i++) {
			do {
				number = (int)(Math.random()*33)+1;
			} while (isExist(number,redNum));
			redNum[i] = number;
		}
		order(redNum);
		
		int blueNum = (int)(Math.random()*16)+1;
		
		StringBuffer buffer = new StringBuffer();
		for (int i = 0; i < 6; i++) {
			buffer.append(redNum[i]).append(",");
		}
		buffer.delete(buffer.length()-1, buffer.length());
		buffer.append(" | ").append(blueNum);
		System.out.println("本次双色球中将号码是:");
		System.out.println(buffer.toString());
	}
	
	public static void order(int [] redNum){
		for (int i = 0; i < 5; i++) {
			for (int j = i+1; j < 6; j++) {
				int t = 0;
				if (redNum[i] > redNum[j]) {
					t = redNum[i];
					redNum[i] = redNum[j];
					redNum[j] = t;
				}
			}
		}
	}
	
	public static boolean isExist(int number,int [] redNum){
		for (int i = 0; i < 6; i++) {
			if (number == redNum[i]) {
				return true;
			}
		}
		return false;
	}
}

参考code:

package my.doublecolorball;  
public class DoubleColorBall {  
    public static void main(String[] args) {  
        int[] numbers = new int[7];  
        int num = 0;  
        //产生6个红球  
        //for循环产生数组的时候,首先要进行判断,如果存在,继续产生随机数,用do-while循环来控制
        for(int i=0;i<6;i++){  
            do{  
                num = (int) (Math.random()*33)+1;  //利用Math.random来完成从1~33中选6个红球出来
            }while(isExist(num,numbers));//判断新产生的随机数是不是已经在数组中存在了  
            numbers[i] = num;//如果不存在,就把该数字放入数组中  
        }  
        order(numbers);//调用排序的方法  
  
        //产生一个蓝球  
        numbers[6] = (int)(Math.random()*16)+1;  
  
        //构造输出的字符串  
        StringBuffer buffer = new StringBuffer();  
        //利用StringBuffer的append-拼接方法来实现遍历输出数组中的内容,用“,”分割开
        for(int i=0;i<6;i++){  
            buffer.append(numbers[i]).append(",");//用逗号分隔开  
        }  
        buffer.delete(buffer.length()-1, buffer.length());//删除最后一个逗号  
        buffer.append(" + ").append(numbers[6]);  
        System.out.println("双色球预测号:\n"+buffer.toString());//buffer的toString方法可以将StringBuffer对象转换为String  
        System.out.println("\n预祝你早日中大奖!");  
    }  
  
    /**对数组排序*/  
    //对以上产生的数组中的6个红球进行排序,此排序实则为冒泡排序,冒泡排序是一个基本算法
    private static void order(int[] numbers){  
        for(int i=0;i<5;i++){  
            for(int j=i+1;j<6;j++){  
                int temp = 0;  
                if(numbers[i]>numbers[j]){  
                    temp = numbers[i];  
                    numbers[i] = numbers[j];  
                    numbers[j] = temp;  
                }  
            }  
        }  
    }  

    //选出的红球不能重复,但是随机数是有可能重复的,所以定义一个数组来存储产生的红球,并且存入数组之前,先判断当前产生的随机数是不是已经存在数组中了。
    /**判断当前产生的数在数组中是否已经存在*/  
    private static boolean isExist(int num,int[] numbers){  
        for(int i=0;i<6;i++){  
            if(num == numbers[i]){  
                return true; //已经存在此数  
            }  
        }  
        return false; //不存在此数  
    }  
} 


练习1:编写程序将 “jdk” 全部变为大写,并输出到屏幕,截取子串”DK” 并输出到屏幕。

package com.liudm.demo11;

public class Test1 {
	public static void main(String[] args) {
		String str = "jdk";
		System.out.println(str.toUpperCase());  //toUpperCase:小写转换为大写
		System.out.println(str.toUpperCase().substring(1));  //substring:截取,从指定字符到最后一个字符
	}

}

 

练习2:编写程序将String类型字符串”test” 变为 “tset”.

package com.liudm.demo11;

public class Test2 {
	public static void main(String[] args) {
		String str = "test";
		System.out.println(str);
		System.out.println(str.replace("es", "se")); //replace:替换
	}
}

 

练习3:写一个方法判断一个字符串是否对称

package com.liudm.demo11;

public class Test3 {
	public static void main(String[] args) {
		System.out.println(Test3.isSymmetry("abc"));
		System.out.println(Test3.isSymmetry("abcba"));
		System.out.println(Test3.isSymmetry("123"));
		System.out.println(Test3.isSymmetry("1234321"));
	}
	public static boolean isSymmetry (String str) {
		
		for (int i = 0; i < str.length() / 2; i++) {
			if (str.charAt(i) != str.charAt(str.length() - i - 1)) {
				return false;
			} else {
				return true;
			}
		}
		return true;
	}
}
//还可以把整个字符串转制后,用equals()方法判断转制前后字符串是否相同

 

练习4:编写一个程序,将下面的一段文本中的各个单词的字母顺序翻转,“To be or not to be",将变成"oT eb ro ton ot eb"。

package com.liudm.demo11;

public class Test4 { 
	public static void main(String[] args) {
		String str = new String("To be or not to be");
		String ss[] = str.split(" ");     //split():String
		System.out.print("拆分单词:");
		for (int i = 0; i < ss.length; i++) {
			System.out.print(ss[i] + " ");
		}
		System.out.println();
		
		System.out.print("拆分后转制:");
		//StringBuffer [] s= new StringBuffer[]{};
		for (int i = 0; i < ss.length; i++) {
			StringBuffer s = new StringBuffer(ss[i]);     //reverse():StringBuffer
			System.out.print(s.reverse() + " ");
		}
	}
}

 

练习5:String s=”name=zhangsan age=18 classNo=090728”,将上面的字符串拆分,结果如下:zhangsan 180 90728。

package com.liudm.demo11;

public class Test5 {
	public static void main(String[] args) {
		String s = "name=zhangsan age=18 classNo=090728";
		String [] c = s.split(" ");  //按空格拆分
		String [] sNew = new String[c.length];
		for (int i = 0; i < c.length; i++) {
			sNew[i] = c[i].substring(c[i].indexOf("=")+1, c[i].length());  //从=下标的下一个字符开始截取
		}
		for (int i = 0; i < sNew.length; i++) {
			System.out.print(sNew[i] + " ");
		}
	}
}

 

练习6:输入一行字符,分别统计出英文字母,空格,数字和其他字符的个数。

练习7:密码自动生成器,随机生成一个四位数的密码,由字母、数字、或者下划线组成。

练习8:输入一个秒数,要求转换为xx小时xx分xx秒的格式输出出来。

练习9:显示批发商品信息;输入批发商品编号和数量,以指定格式显示价格和总金额。

练习10:实现用户注册,要求用户名长度不小于3,密码长度不小于6,注册时两次输入密码必须相同。

练习11:判断.java文件名是否正确,判断邮箱格式是否正确。

练习12:输入一个字符串(不含空格),输入一个字符,判断该字符在该字符串中出现的次数。

练习13:有一段歌词,每句都以空格“ ”结尾,请将歌词每句按行输出。

练习14:计算2012年5月6日是一年中的第几星期。

猜你喜欢

转载自blog.csdn.net/weixin_42526141/article/details/82848464