Scanner scan = new Scanner(System.in);
System.out.println("나이입력: ");
int age = scan.nextInt();
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( )를 그냥 사용해서 버퍼에 들어있는 입력값을 초기화시키고 사용을 해야 바로 넘어가버리는 불상사가 나지 않는다. 주의하자!//값 지정시 파이썬과는 달리 {}중괄호를 이용해서 그 안에 값을 넣으면 된다.
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));
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(
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);
}
}
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()를 사용한다.
값이 존재할 때 어느 위치에 존재하는지 알고 싶은 경우 indexOf()를 사용할 수 있다
값이 존재하지 않을 경우 -1을 리턴하기 때문에 별도로 처리가 가능합니다.