스터디사이트 : https://www.hackerrank.com


JAVA 알고리즘 : 간단 배열 합


자바 코딩을 이용하여 아래와 같이 입력되면 아래와 같이 출력되게 코딩 해 보시오


입력 : Scanner 클래스 이용.  Scanner scan = new Scanner(System.in)

출력 : System.out.println(출력);


입력

6입력 배열의 사이즈.

1 2 3 4 10 11 실제 입력값


출력

31실제 입력값들의 합




코딩연습-1

- Scanner클래스의 기본적인 구분자는 사이띄개 인 것으로 확인하였다.

확인방법은 아래처럼 scan변수명으로 Scanner클래스를 정의했다고 하면. scan.delimiter() 메소드를 System.out.println()으로 묶어서 콘솔에 출력해 보면 된다.

그러면 결과는 \p{javaWhitespace}+ 로 나온다. 그래서 알게됐다..

- 순서대로 값이 저장되는 java.util.ArrayList 클래스를 이용하여 입력값을 차곡차곡 저장해서 프린트 테스트를 해 보았다.

public static void main(String[] args) { Scanner scan = new Scanner(System.in); List<integer> scanint = new ArrayList<integer>(); int size= scan.nextInt(); for(int i = 0 ; i < size; i++){ scanint.add(scan.nextInt()); System.out.println("output a1 : " + scanint.get(i)); } System.out.println("Finished"); } 

결과 :

6

1

output a1 : 1

2 3 4 5 6

output a1 : 2

output a1 : 3

output a1 : 4

output a1 : 5

output a1 : 6

 

Finished

 



코딩연습 - 2 & 결과

원하는대로 코딩준비를 다 한것 같으니, ArrayList에 저장된 Integer값들을 모두 합해서 출력하는 일만 남은 듯하다.

결과값을 받는 int sum 을 추가하여 for문 안에서 입력된 Integer값을 sum값에 넣어서 더해보자

public static void main(String[] args) { Scanner scan = new Scanner(System.in); List<Integer> scanint = new ArrayList<Integer>(); int size= scan.nextInt(); int sum=0; for(int i = 0 ; i < size; i++){ scanint.add(scan.nextInt()); sum=sum+scanint.get(i); } System.out.println("sum : " + sum); }

결과 :

6

1 2 3 4 5 6

sum : 21


+ Recent posts