从零开始的Java再学习-DAY15

基本算法

1.输入10个随机数并能从小到大排序:

import java.util.Scanner;

public class Base_MP {
    public static void main(String[] args) {
        int[] a=new int[10];

        //交互
        System.out.println("请输入数字(10个):");
        Scanner scanner=new Scanner(System.in);
        if (scanner.hasNextInt()){
            for (int i = 0; i < a.length; i++) {
                a[i]=scanner.nextInt();
            }

        }

        //冒泡
        for (int i = 0; i < a.length-1; i++) {
            for (int j=0;j<a.length-1-i;j++){
                if (a[j]>a[j+1]){
                    int x=a[j];
                    a[j]=a[j+1];
                    a[j+1]=x;
                }

            }
        }
        //输出数组
        System.out.print("数字从小到大排列后为:{");
        for (int x=0;x<a.length;x++){
            System.out.print(a[x]+" ");
        }
        System.out.println("}");
    }
}

/*结果:
请输入数字(10个):
9
5
7
6
4
8
1
3
2
11
数字从小到大排列后为:{1 2 3 4 5 6 7 8 9 11 }

Process finished with exit code 0
*/

2.输入10个随机数并能根据输入的数得出连续相加最大的值

import java.util.Scanner;

public class Base_MP {
    public static void main(String[] args) {
        int[] a=new int[10];

        //交互
        System.out.println("请输入数字(10个):");
        Scanner scanner=new Scanner(System.in);
        if (scanner.hasNextInt()){
            for (int i = 0; i < a.length; i++) {
                a[i]=scanner.nextInt();
            }

        }
        int[] b=new int[10];
        //复制一份
        for (int i = 0; i < a.length; i++) {
            b[i]=a[i];
        }

        //冒泡
        for (int i = 0; i < a.length-1; i++) {
            for (int j=0;j<a.length-1-i;j++){
                if (a[j]>a[j+1]){
                    int x=a[j];
                    a[j]=a[j+1];
                    a[j+1]=x;
                }

            }
        }

        //寻找相加最大的一连串数
        int max=a[a.length-1];
        System.out.println("最大数:"+GetMax(b, max));

    }

    public static int GetMax(int[] arr,int t_max){
        for (int i=0;i<arr.length-1;i++){
            int temp=0;//每轮重置相加值
            for (int j=i;j<arr.length-1;j++){
                temp+=arr[j];//从左加到右
                if (temp>t_max){
                    t_max=temp;
                }

            }
        }
        return t_max;
    }
}

/*
请输入数字(10个):
-1
4
-8
-6
7
8
5
-3
4
-9
最大数:21

Process finished with exit code 0

*/
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值