본문 바로가기
JAVA/개념정리

[JAVA] Array의 활용

by JJH0100 2022. 10. 5.
728x90
반응형

최대값과 최소값 구하기

public class ArrayTest2 {
	public static void main(String[] args) {
		int score[] = {55, 45, 34, 3, 4, 23, 45, 34, 56};
        
        //최대값 구하기
		int max = score[0];
		for(int i=1; i<score.length; i++) {
			if(score[i] > max)
				max = score[i];
		}
		System.out.println("최대 값은 : " + max);
		
        //최소값 구하기
		int min = score[0];
		for(int i=1; i<score.length; i++) {
			if(score[i] < min)
				min = score[i];
		}
		System.out.println("최소 값은 : " + min);
	}
}

 

 

찾고 싶은 숫자의 갯수 구하기

import java.util.Scanner;
public class ArrayTest3 {
	public static void main(String[] args) {
		int num[] = {6, 5, 3, 5, 2, 5, 7, 1, 4, 7, 4};
		Scanner sc = new Scanner(System.in);
		
		System.out.print("찾고 싶은 숫자를 입력해 주세요 >> ");
		
		int key = sc.nextInt();
		int count = 0;
		for(int i=0; i<num.length; i++) {
			if(num[i] == key) {
				count++;
				System.out.println((i+1) + "번째 데이터와 일치");
			}
		}
		if(count == 0) {
			System.out.println(key + "값은 배열에 존재하지 않습니다.");
		}else {
			System.out.println(key + " 값이 배열에 " + count + "개 있습니다.");
		}
	}
}

 

양의 정수 10개를 받아 배열에 저장하고, 저장된 배열에서 3의 배수만 출력하는 프로그램을 작성하시오.

import java.util.Scanner;
public class Quiz01 {
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		int i;
		int dnum[] = new int[10];
		
		//데이터를 입력
		System.out.print("양의 정수 10개를 입력하시오 : ");
		for(i=0; i<dnum.length; i++) {
			dnum[i] = sc.nextInt();
		}
		System.out.println();
		
		// 3의 배수 구하기
		System.out.print("3의 배수는 ");
		for(i=0; i<dnum.length; i++) {
			if((dnum[i]%3) == 0) {
				System.out.print(dnum[i] + " ");
			}
		}
	}
}

728x90
반응형

'JAVA > 개념정리' 카테고리의 다른 글

[JAVA] 생성자 - 묵시적 생성자, 명시적 생성자  (2) 2022.10.07
[Java] System.arraycopy  (0) 2022.10.06
[JAVA] Array  (0) 2022.10.05
[JAVA] 클래스와 메소드  (0) 2022.10.04
[JAVA] IF문의 활용  (2) 2022.09.16

댓글