Java & Spring/Java

[JAVA] ์ž๋ฐ”์˜ Array : Compare, fill, sort

Rainbow๐ŸŒˆCoder 2022. 12. 17. 15:47
728x90

1. ํ–ฅ์ƒ๋œ loop

public class App {
    public static void main(String[] args) throws Exception {
        //[1] Input : n๋ช…์˜ ๊ตญ์–ด ์ ์ˆ˜
        int[] scores = {100, 75, 3 ,5 ,3, 22, 34};
        int sum = 0;
                
        //[2] Process
        for (int i = 0; i < scores.length; i++) {
            sum += scores[i];
        }
                
        //[3] Output
        System.out.println(sum);
        
        
        
        int sum1 = 0;
        for (int x : scores) {
             sum1 += x;
        }

        System.out.println(sum1);
    }
}

        int[] scores = {100, 75, 3 ,5 ,3, 22, 34};
        int sum = 0;
                
        //[2] Process
        for (int i = 0; i < scores.length; i++) {
            sum += scores[i];
        }
        
        int sum1 = 0;
        for (int x : scores) { //x๊ฐ€ ๊ณง scores[์ˆœ์„œ๋Œ€๋กœ] ์˜ ๊ฐ’์ด ๋˜๋Š”... ๋Œ€๋‹จํžˆ ๊ฐ„ํŽธํ•œ ์ž๋ฐ”์‹!
             sum1 += x;
        }

 

 

2. Arrays.fill

import java.util.Arrays;

public class App {
    public static void main(String[] args) throws Exception {
        int[] scores = new int[5];
        for(int x : scores){
            System.out.println(x);
        }
        Arrays.fill(scores,100);
        for(int x : scores){
            System.out.println(x);
        }
    }
}

์ถœ๋ ฅ๊ฒฐ๊ณผ

0

0

0

0

0

100

100

100

100

100

 

3. Arrays.equal

import java.util.Arrays;

public class App {
    public static void main(String[] args) throws Exception {
        int[] englishScores = new int[5];
        int[] mathScores = {34,45,56,22,18};
        int[] artScores = {34,45,56,22,18};

        System.out.println( Arrays.equals(mathScores,artScores)); // true
        System.out.println( Arrays.equals(mathScores,englishScores)); // false
    }
}

4. Arrays.sort

 

 

import java.util.Arrays;

public class App {
    public static void main(String[] args) throws Exception {
        int[] mathScores = {34,45,56,22,18};
        Arrays.sort(mathScores);
        for(int x : mathScores){
            System.out.println(x); // 18 22 34 45 56
        }
    }
}
728x90