Java基础算法

目录

Java_99乘法表

Java_冒泡排序

Java_斐波那契额数列

Java_数组最大值

Java_数组反转

Java_数组总和

Java_将文本信息恢复顺序

Java_水仙花数

Java_求1-100之间的偶数和

Java_简单用户登录

Java_遍历字符串案例

Java_统计字符次数案例

Java_数组转成字符串拼接

Java_字符串反转案例

Java_求三个数最大值

Java_ArrayList数组去重

Java_求年龄工具类


Java_99乘法表

public class Main {
	public static void main(String[] args) {
		for (int i = 1; i <10; i++) {
            //0. 1开始, 1<=1
			for (int j = 1; j <= i; j++) {
                //1. 不换行
				System.out.print(j + "*" + i + "=" + i * j + "  ");
			}
			System.out.println();
		}
    }
}

Java_冒泡排序

public class MaoPao {
    public static void main(String[] args){
        int[] arrays = {4,2,3,1,5,8,9,6};
        msort(arrays);
        for(int i=0;i<arrays.length;i++){
            System.out.println(arrays[i]);
        }
    }

    public static  int[] msort(int[] arrays){
        for(int i=0;i<arrays.length;i++){
            // 使用一个boolean类型来记录是否进行了交换。如果没有交换,意味着数组已经正序,直接退出比较
        	boolean flag = false;
            for(int j=0;j<arrays.length-1-i;j++){
                if(arrays[j]>arrays[j+1]){
                    int temp = arrays[j];
                    arrays[j]=arrays[j+1];
                    arrays[j+1]=temp;
                    flag=true;
                }
            }
            if(flag==false){
                break;
            }
        }
        return arrays;
    }
}

Java_斐波那契额数列

public class Main {
    public static void main(String[] args) {
        for (int a = 0; a <= 10; a++){
            System.out.println(f(a));
        }
    }
 
    public static long f(long number) {
        if ((number == 0) || (number == 1))
            return number;
        else
            return f(number - 1) + f(number - 2);
    }
}

Java_数组最大值


public class Main {
    public static void main(String[] args) {
        int[] arr = {1,2,3,4,5,6,6};
        //0. 第三方值
        int sum = arr[0];
        //1. 每次循环跟数组索引为0的元素比较大小
        for (int i = 0; i < arr.length; i++){
            if (sum < arr[i]){
                //2. 大于新值重新覆盖
                sum = arr[i];
            }
        }
        System.out.println(sum);
    }
 
}

Java_数组反转

import java.util.Arrays;
public class Main {
    public static void main(String[] args) {
        String[] arr = reverseArray(new String[]{"1","2","3"});
        System.out.println(Arrays.toString(arr));
    }
    
    public static String[] reverseArray(String[] Array) {  
        String[] new_array = new String[Array.length];  
        for (int i = 0; i < Array.length; i++) {  
            // 反转后数组的第一个元素等于源数组的最后一个元素:  
            new_array[i] = Array[Array.length - i - 1];  
        }  
        return new_array;  
    }  
 
}

Java_数组总和

public class Main {
	public static void main(String[] args) {
	    int[] arr = {2,3,5};
        //0. 拉上第三方变量
		int sum=0;
        for(int i =0;i<arr.length;i++){ 
              sum+=arr[i]; 
        }
        System.out.println(sum);
	}
}

Java_将文本信息恢复顺序

public class Demo04Test {
    public static void main(String[] args) throws IOException {
        Map<String,String> map = new HashMap<>();
        BufferedReader br = new BufferedReader(new FileReader("day\\in.txt"));
        BufferedWriter bw = new BufferedWriter(new FileWriter("day\\out.txt"));
        //1.使用BufferedReader对象readLine,以行的方式读取文本
        String line;
        while((line = br.readLine())!=null){
            //2.对读取的每行文本进行切割,把序号和文本内容存储到一个String数组
            String[] arr = line.split("\\.");
            //3.把序号和文本内容存储到Map集合中(key会进自然排序)
            map.put(arr[0],arr[1]);
        }
        Set<Map.Entry<String, String>> set = map.entrySet();
        for (Map.Entry<String, String> entry : set) {
            String key = entry.getKey();
            String value = entry.getValue();
            //4.使用BufferedWriter对象中的方法write,把键值对拼接在一起写在内存缓冲区中
            bw.write(key+"."+value);
            //5.写换行
            bw.newLine();
        }
        bw.close();
        br.close();
    }
}

Java_水仙花数

public class Main {
	public static void main(String[] args) {
		for(int i = 100; i <= 999; i++){
			int ge = i % 10;
			int shi = i / 10 % 10;
            //0. 求百位
			int bai = i / 100 % 10;
			if(	(ge*ge*ge + shi*shi*shi + bai*bai*bai) == i){
				System.out.println(i);
			}
		}
	}
}

Java_求1-100之间的偶数和

public class ForSum100 {
    public static void main(String[] args) {
        int sum = 0;
        for (int i = 1; i <= 100; i++) {
            if (i % 2 == 0) {
                sum += i;
            }
        }
        System.out.println("1-100之间的偶数数字之和: "+sum);
 


        //0. 注意这两种写法
        for (int j = 0; j <= 100; j++,j++/*j+=2*/) {
            sum += j;
        }
    }
}

Java_简单用户登录

public class Test {
    public static void main(String[] args) {
        /*
            需求:已知用户名和密码,请用程序实现模拟用户登录。总共给三次机会,登录之后,给出相应的提示
         */

        String username = "admin";
        String password = "123456";
        for (int i = 0; i < 3; i++) {
            //0. 每次循环, 用户键盘录入用户名和密码
            Scanner sc = new Scanner(System.in);
            System.out.println("请输入用户名:");
            String name = sc.next();
            System.out.println("请输入密码:");
            String pwd = sc.next();

            if (username.equals(name) && password.equals(pwd)) {
                System.out.println("恭喜您,登录成功!");
                break;
            } else {
                if (i == 2){
                    System.out.println("很遗憾,登录失败,您的账号已被锁定,请充钱解锁!");
                }else{
                    System.out.println("很遗憾,登录失败,您还有"+(2-i)+"次机会");
                }
            }
        }
    }
}

Java_遍历字符串案例

public class Test {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("请输入一个字符串:");
        String str = sc.next();
        for (int i = 0; i < str.length(); i++) {
            //0. 通过charAt方法字符
            char c = str.charAt(i);
            System.out.println(c);
        }
    }
}

Java_统计字符次数案例

public class Test {
    public static void main(String[] args) {
        // 需求:键盘录入一个字符串,统计该字符串中大写字母字符,小写字母字符,数字字符出现的次数(不考虑其他字符)
        Scanner sc = new Scanner(System.in);
        System.out.println("请输入一个字符串:");
        String str = sc.next();

        //0. 定义一个int类型的变量,用来统计大写字母字符个数
        int count1 = 0;
        int count2 = 0;
        int count3 = 0;

        for (int i = 0; i < str.length(); i++) {
            char c = str.charAt(i);
            // 5.在循环中,判断该字符:
            if (c >= 'A' && c <= 'Z') {
                // 5.如果该字符是大写字母字符,那么统计大写字母字符个数的变量+1
                count1++;
            } else if (c >= 'a' && c <= 'z') {
                // 5.如果该字符是小写字母字符,那么统计小写字母字符个数的变量+1
                count2++;
            } else if (c >= '0' && c <= '9'){
                // 5.如果该字符是数字字符,那么统计数字字符个数的变量+1
                count3++;
            }
        }
        System.out.println("大写字母字符个数:"+count1);
        System.out.println("小写字母字符个数:"+count2);
        System.out.println("数字字符个数:"+count3);

    }
}

Java_数组转成字符串拼接

public class Test {
    public static void main(String[] args) {
        int[] arr = {1,2,3};
        System.out.println(arrayToString(arr));// [1, 2, 3]
    }

    public static String arrayToString(int[] arr) {
        //0. 创建空白的字符串对象
        String str = "";

        for (int i = 0; i < arr.length; i++) {
            //1. 获取每个数字
            int e = arr[i];
            //2. 索引0开始
            if (i == 0) {
                str += "[" + e + ", ";
            } else if (i == arr.length - 1) {
                //3. 为最后一个数
                str += e + "]";
            } else {
                str += e + ", ";
            }
        }
        return str;
    }
}

Java_字符串反转案例

public class Test {
    public static void main(String[] args) {
        /*
            需求:
            定义一个方法,实现字符串反转。键盘录入一个字符串,调用该方法后,在控制台输出反转后的字符串
            例如,键盘录入 abc,输出结果 cba
         */
        // 键盘录入一个字符串
        Scanner sc = new Scanner(System.in);
        System.out.println("请输入一个字符串:");
        String str = sc.next();
        System.out.println(reverse(str));
    }


    public static String reverse(String str){
        String newStr = "";
        //0. 倒叙遍历传入的字符串对象
        for (int i = str.length()-1;i >= 0; i--) {
            char c = str.charAt(i);
            newStr += c;
        }
        //1. 返回反转后的字符串
        return newStr;
    }


    //第二种
    public static String reverse3(String str) {
        String reverse = "";
        for (int i = 0; i < str.length(); i++) {
              reverse = str.charAt(i) + reverse;
        }
        return reverse;
    }
}

Java_求三个数最大值

public class Demo02Max {
    public static void main(String[] args) {
        //1.定义3个int变量a,b,c,并分别初始化
        int a = 100, b = 200,c = 300;

        //2.假设变量a的值是最大的,把a保存到int变量max中
        int max = a;

        //3.如果变量b的值大于max,说明max中的值目前不是最大的,把b的值赋值给max
        if (b > max) {
            max = b;
        }
        //4.如果变量c的值大于max,说明max中的值目前不是最大的,把c的值赋值给max
        if (c > max) {
            max = c;
        }
        //5.打印max的值
        System.out.println("最大值: "+max);
    }
}

Java_ArrayList数组去重

    ArrayList list = new ArrayList();
        list.add("aaa");
        list.add("aaa");  

  //1.循环list中所有的元素然后删除
    public static ArrayList removeDuplicate_1(ArrayList list){
        //1.1. -1是去掉最大数, 因为有默认了
        for(int i =0;i<list.size()-1;i++){
            for(int j=list.size()-1;j>i;j--){
                if(list.get(i).equals(list.get(j)))
                    //1.2. 从后面删除的, 没有异常
                    list.remove(j);
            }
        }
        
        return list;        
    }
    

    //2.利用hashSet剔除重复元素,但是是无序的
    public static ArrayList removeDuplicate_2(ArrayList list){
        HashSet set = new HashSet(list);
        //使用LinkedHashSet可以保证输入的顺序
        //LinkedHashSet<String> set2 = new LinkedHashSet<String>(list); 
        list.clear();        
        list.addAll(set);
        return list;        
    }
    

    //3.利用list的contains方法去重
    public static ArrayList removeDuplicate_3(ArrayList list){
        ArrayList tempList = new ArrayList(list.size());
        for(int i=0;i<list.size();i++){
            if(!tempList.contains(list.get(i)))
                tempList.add(list.get(i));
        }
        return tempList;        
    }

​​​​​​​Java_求年龄工具类

public class Utils {

    // 定义一个静态的id变量, 用来给学生对象的id赋值
    public static int id ;// 100个对象 id=100 程序停止再启动
    public static int tid ;// 100个对象 id=100 程序停止再启动

    static {
        id = 0;// 以后可以读取文件中记录的id值,赋为初始值
        tid = 0;
    }


    // 根据生日计算年龄的方法
    public static int birthdayToAge(String birthday){
        // 思路:
        // 1. 获取当前日期对象
        Date nowDate = new Date();

        // 2. 创建日期格式化对象,指定日期格式
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

        // 3. 调用parse()解析方法对字符串生日解析为Date类型的生日
        Date birthdayDate = null;
        try {
            birthdayDate = sdf.parse(birthday);
        } catch (ParseException e) {
            e.printStackTrace();
        }

        // 4.比较出生日期是否在当前日期之后,如果是,直接返回 -1;
        if (birthdayDate.after(nowDate)) {
            return -1;
        }
        // 5.获取当前时间的日历对象
        Calendar cal = Calendar.getInstance();

        // 6.获取当前时间的年,月,日
        int nowYear = cal.get(Calendar.YEAR);
        int nowMonth = cal.get(Calendar.MONTH);
        int nowDay = cal.get(Calendar.DAY_OF_MONTH);

        // 7.通过日历对象调用setTime(Date date)方法,设置日历对象的时间为出生日期的时间
        cal.setTime(birthdayDate);

        // 8.通过设置之后的日历对象获取生日的年,月,日
        int birthdayYear = cal.get(Calendar.YEAR);
        int birthdayMonth = cal.get(Calendar.MONTH);
        int birthdayDay = cal.get(Calendar.DAY_OF_MONTH);

        // 9.使用当前时间的年 - 生日的年 得到一个初步的年龄
        int age = nowYear - birthdayYear;

        // 10.如果当前时间的月 小于 生日的月份,那么初步年龄-1
        if (nowMonth < birthdayMonth){
            age--;
        }

        // 11.如果当前时间的月 等于生日的月份,但当前时间的日 小于 生日的日,那么初步年龄-1
        if (nowMonth == birthdayMonth){
            if (nowDay < birthdayDay){
                age--;
            }
        }
        // 10.直接返回年龄
        return age;
    }
}
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值