JAVA(3)_입출력, 배열과 ArrayList

Wooney98·2022년 11월 3일
1

JAVA

목록 보기
3/8
post-thumbnail

입출력

  • 입력
    • Scanner 클래스를 이용하여 입력을 받거나 System.in.read()를 이용해 입력받는다.
Scanner scan = new Scanner(System.in);
System.out.println("나이입력: ");
int age = scan.nextInt();
  • System.in.read( ) 는 조금 다른데 모든 입력이 아스키코드로 입력이 된다. 숫자를 입력하든 문자를 입력하든 받는 단어 하나마다 아스키코드로 변환해서 받는다. 그래서 엔터를 입력하기 전까지 조건을 주어 입력하는 경우가 많다. 또한 무슨 입력이 들어올지 모르기 때문에 에러Exception을 넣어준다.
int ch = 0;
		
while( (ch = System.in.read()) != '\n' ) {
		System.out.print(ch+"\t");
}
// 정수입력 >> 32
// 51  50  13   
//여기서 51은 3에 대한 아스키코드. 50은 2에 대한 아스키코드. 
	13은 엔터에 대한 아스키코드이다.
  • 정수를 입력받고싶다면?
// 정수가 return된다. 엔터를 입력 받기 전까지 계속 입력받는다. 
// 엔터 받으면 while을 종료한다
while( (ch = System.in.read()) != '\n' ) { 
// 입력받은 숫자의 자리 하나만큼 실행. 숫자를 한개씩 입력할 때 마다 실행된다. 
// 엔터를 쳐야 값이 보이지만 그 전에는 자동으로 처리하는 중이다.
			if(ch >= '0' && ch <='9') { 
				num *= 10; //자리수를 올림. 시작은 1의 자리이기 때문에 0부터 하는것이 맞음. 
				num += ch-'0'; //0에 대한 아스키값을 뺌. 그러면 실제 숫자가 
               				 //num에 들어가게 된다. 0~9 사이의 숫자가 들어감.
			}
		}

//여담으로 int a = 'c'; 이렇게 하면 c에 대한 아스키코드 값이 a에 숫자로 저정함
  • scan.next( )scan.nextline( ) 의 차이점
    • next( )는 스페이스(공백)을 받기 전까지의 문자열을 입력받는다
    • nextline( ) 은 enter를 치기 전까지의 문자열을 입력받는다. nextline( ) 을 사용시 주의해야할 점이 있는데 만약 nextline( )을 사용하기 전에 nextInt( ) 를 사용했으면 이것은 enter를 기준으로 정수를 입력받는데 사용하고 난 후 enter값이 남아있기 때문에 nextline( )을 사용하게 되면 enter의 값을 읽어들여서 바로 넘어가버린다. 그래서 nextline( )을 사용하기 전에는 nextline( )을 재사용하거나 next( )를 그냥 사용해서 버퍼에 들어있는 입력값을 초기화시키고 사용을 해야 바로 넘어가버리는 불상사가 나지 않는다. 주의하자!

배열과 ArrayList

  • 자바 배열은 배열과 ArrayList가 존재.
  • 배열 역시 객체이다. int [] array = new int[4] 이렇게도 선언하기 떄문에 new가 있어서 객체이다.
  • 배열 객체 생성시 배열 변수는 스택 메모리에 값이 할당된다
  • 배열 값. 즉 실제로 배열에 들어가는 값은 힙 메모리에 저장이 된다. 힙 메모리에 배열의 갯수만큼 메모리가 할당되며 int면 4바이트씩 문자면 2바이트씩 메모리에 붙어서 할당이 된다.
  • 그리고 일반적으로 배열 변수의 다른 배열을 할당하면 그 배열의 주소가 복사되는 얕은 복사가 이루어진다. 그러면 주소가 복사되기 때문에 다른 변수에서 값을 수정할 수 있다.
  • 배열은 정적 할당(크기 지정해야함). ArrayList는 동적 할당(크기 지정 안해도 됨)의 차이가 있다. 배열은 선언하고 사용하기 전에 무조건 배열의 크기를 지정해주어야 한다.
  • 왠만해선 ArrayList로 사용하자 배열 불편한것이 너무 많음.

배열 사용 방법

//값 지정시 파이썬과는 달리 {}중괄호를 이용해서 그 안에 값을 넣으면 된다.
int n[][] = { {1}, {1,2,3}, {1}, {1,2,3,4}, {1,2}};
int[] unit = {50000,10000,1000,500,100,50,10,1};
int [][] array = new int[4][4]; //2차원 배열 생성. 
int arr[] = new int[4]; //이렇게 선언해주어야 한다.

//배열에 값 넣는 방식
for (int i=0; i<4; i++) {
			for (int j=0; j<4; j++) {
				array[i][j] =  ran.nextInt(10)+1;
				System.out.print(array[i][j]+"\t");
			}
			System.out.println();
		}

//중요! 배열은 파이썬처럼 System.out.print(array); 하면 해당 배열의 주소값이 찍힌다
//배열의 값을 출력할 때 ArrayList로 바꿔서 사용해서 한다.
//배열 출력 시 파이썬처럼 그냥 arr하는게 아닌 Arrays.toString(변수명)을 입력해야한다
System.out.println(Arrays.toString(array));

//2차원 배열을 for문 안쓰고 모두 출력하는 방법
System.out.println(Arrays.deepToString(array));

ArrayList 사용 방법

import java.util.ArrayList; //자바에서 ArrayList를 사용하기위해 추가

ArrayList<Integer> integers1 = new ArrayList<Integer>(); // 타입 지정
ArrayList<Integer> integers2 = new ArrayList<>(); // 타입 생략 가능
ArrayList<Integer> integers3 = new ArrayList<>(10); // 초기 용량(Capacity) 설정
ArrayList<Integer> integers4 = new ArrayList<>(integers1); // 다른 Collection값으로 초기화
ArrayList<Integer> integers5 = new ArrayList<>(Arrays.asList(1, 2, 3, 4, 5)); // Arrays.asList(

ArrayList 추가, 변경, 삭제

import java.util.ArrayList;

public class ArrayListTest {
    public static void main(String[] args) {
        ArrayList<String> colors = new ArrayList<>();
        // add() method
        colors.add("Black");
        colors.add("White");
        colors.add(0, "Green");
        colors.add("Red");

        // set() method
        colors.set(0, "Blue");
        
        // remove() method
        colors.remove("White");

        System.out.println(colors);
    }
}
  • add()는 기본적으로 리스트의 가장 끝에 값을 추가한다.
  • set() 메소드를 통해 가장 앞(Index: 0)의 Green이 Blue로 변경한다.
  • remove() 메소드를 통해 추가했던 인덱스를 삭제한다.

ArrayList 전체 값 확인

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.ListIterator;

public class ArrayListTest {
    public static void main(String[] args) {
        ArrayList<String> colors = new ArrayList<>(Arrays.asList("Black", "White", "Green", "Red"));
        // for-each loop
        for (String color : colors) {
            System.out.print(color + "  ");
        }
        System.out.println();

        // for loop
        for (int i = 0; i < colors.size(); ++i) {
            System.out.print(colors.get(i) + "  ");
        }
        System.out.println();

        // using iterator
        Iterator<String> iterator = colors.iterator();
        while (iterator.hasNext()) {
            System.out.print(iterator.next() + "  ");
        }
        System.out.println();

        // using listIterator
        ListIterator<String> listIterator = colors.listIterator(colors.size());
        while (listIterator.hasPrevious()) {
            System.out.print(listIterator.previous() + "  ");
        }
        System.out.println();
    }
}
  • for-each 반복문으로 각각의 값을 순회해서 출력하는 것이 가능하다.

  • 또한 get() 메소드로 각 인덱스의 값을 순차적으로 탐색하는 방법도 가능하다.

  • 그리고 iterator나 listIterator를 통해 값들을 순회하는 것도 가능하다.

  • listIterator의 경우 생성 시 ArrayList의 크기를 입력해주고 역방향으로 출력할 수 있다.

값 존재 유무 확인

import java.util.ArrayList;
import java.util.Arrays;

public class ArrayListTest {
    public static void main(String[] args) {
        ArrayList<String> colors = new ArrayList<>(Arrays.asList("Black", "White", "Green", "Red"));
        boolean contains = colors.contains("Black");
        System.out.println(contains);

        int index = colors.indexOf("Blue");
        System.out.println(index);

        index = colors.indexOf("Red");
        System.out.println(index);
    }
}
  • 값이 존재하는지만 알고 싶은 경우 contains()를 사용한다.

    • contains()는 값이 있는 경우 true를, 값이 없는 경우 false를 리턴합니다.
  • 값이 존재할 때 어느 위치에 존재하는지 알고 싶은 경우 indexOf()를 사용할 수 있다

    • indexOf()는 값이 존재하는 경우 해당 엘레멘트의 인덱스를 리턴합니다.
  • 값이 존재하지 않을 경우 -1을 리턴하기 때문에 별도로 처리가 가능합니다.

profile
👨Education Computer Engineering 🎓Expected Graduation: February 2023 📞Contact info thstjddn77@gmail.com

0개의 댓글