数组,二维数组,方法定义错图总结-关卡二

主要学习内容;

数组,二维数组,方法的定义及使用

1.数组,二维数组,排序,方法定义——错题

求s=a+aa+aaa+aaaa+aa...a的值,其中a是一个数字。例如2+22+222+2222+22222(此时共有5个数相加),几个数相加由用户控制。

分析:第几位数就输出几位数,且是累加的。

import java.util.Scanner;

public class Test28 {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("输入的数字的多少");
        int a = sc.nextInt();
        System.out.println("相加的次数");
        int number = sc.nextInt();
        int sum=0;
        int temp=0;
        for(int i =0;i<number;i++){
            temp=temp*10+a
            sum=sum+temp
            }
            System.out.println(sum);
        }
    }

2.任意一组数组,反转数组

public class reverse {
    public static void main(String[] args) {
        int []arr={19,28,39,66,55,88,44};

        zhuang(arr);
        prinArray(arr);




    }
    public static void zhuang(int[]arr){
        for(int start=0,end=arr.length-1;start<=end;start++,end--){

            int temp=arr[start];
            arr[start]=arr[end];
            arr[end]=temp;
        }
    }




    public static void prinArray(int[]arr){
        System.out.print("[");

        for(int i=0;i<arr.length ;i++){
            if(i<arr.length-1){
                System.out. print(arr[i]+",");
             }else{
                System.out.print(arr[i]);
            }
        }
        System.out.print("]");
    }

}

2.数组反转加冒泡排序(升级版)

 
输出
buddleSort(arr);
方法
public static void buddleSort(int[] arr) {
        int temp = 0;
        for (int i = arr.length - 1; i > 0; i--) {
            for (int j = 0; j < i; j++) {
                if (arr[j] > arr[j + 1]) {
                    temp = arr[j];
                    arr[j] = arr[j + 1];
                    arr[j + 1] = temp;
                }
            }


        }
        System.out.print("[");
        for (int i = 0; i < arr.length; i++) {

            if(i<arr.length-1){
                System.out. print(arr[i]+",");
            }else{
                System.out.print(arr[i]);
            }
        }
        System.out.print("]");
    }

 3,编写程序,从键盘输入一个 0~99999 之间的任意数,判断输入的数是几位数?

int a =sc.nextInt ();
int S=1
int  a=a/10;//注意我用的是INT类型,当a为各位数是为零
whilt(a>0){
    S++
    a  =a/10
}
System.out,println(s);

4.最大值(最小值同理)的调用

 public static int getMax(int[] arr) {
        int max = arr[0];
        for(int x=1; x<arr.length; x++) {
            if(arr[x] > max) {
                max = arr[x];
            }
        }
        return max;

5.遍历数组标准格式

public static void printArray(int[] arr) {
        System.out.print("[");

        for (int x = 0; x < arr.length; x++) {
            if (x == arr.length - 1) {
                System.out.print(arr[x]);
            } else {
                System.out.print(arr[x] + ", ");
            }
        }
        System.out.println("]");
    }
}

猜你喜欢

转载自blog.csdn.net/m0_59619191/article/details/119255011