자바를 자바 05(String/input,output/Control Flow)

TonyHan·2020년 9월 16일
0

20) 자바

목록 보기
4/27

1.5 Strings

변수를 선언하는 것에 있어서도 new를 사용하고 안하고는 큰 차이가 생김

new 를 쓴다는 것은 공간을 생성하여서 값을 대입하는 것이기 때문에

이때 변수에 저장된 것은 메모리 공간의 주소이지 메모리 공간의 값이 저장된 것이 아니다.

String s1 = "Java";
String s2 = "JAVA";

if(s1=="Java") System.out.println("same");
//여기에서 물어보는 것은 같은 객체를 참조하는지 물어보는 것이다.
//동적할당된 객체가 아니기 때문에 same 문구가 출력된다.

if(s1.toUpperCase() == s2) System.out.println("same");
//이 것은 s1의 객체를 가지고 와서 대문자로 바꾼다음 새로운 객체를 반환
//하는 것이기 때문에 값을 비교하는 것이 아닌 여전히 주소를 비교하는 문장이다

String su = s1.toUpperCase();
if(s2.equals(s1)) System.out.println("same");
//그렇기 때문에 가능하다면 객체의 함수를 사용하여서 확인해 주는
//과정이 필요하다.


그렇기 때문에 우리는 String 에 내장되어 있는 다양한 함수들을 그때그때마다 찾아서 사용해 주어야 한다.

1.6 Inputs and Outputs

  • Reading user input
    nextLine 함수는 한 줄을 읽어 들인다.
import java.util.Scanner;

Scanner in = new Scanner(System.in);
System.out.println("What is your name");
String name = in.nextLine();

이외에도
next : 공백이전까지의 문자열을 읽는다.
nextInt : 정수값을 입력으로 받음(문자를 넣으면 에러남)
nextDouble : 실수값을 입력으로 받음(문자를 넣으면 에러남)

등등이 있다.

  • Formatted output
System.out.print() // 출력하고 줄 안바뀜
System.out.println() // 출력하고 줄 바뀜
System.out.printf() // 출력형식 지정 가능

출력 형식
d : int
x : hexadecimal
f : floating
c : character
s : string
b : boolean

  • Flags
  • : 부호 보여주기
  • : 좌측 정렬
    0 : 숫자 앞에 0을 붙여라
    ( : 음수 부호 대신에 괄호를 붙여라
    , : 숫자 3개마다 ','를 붙여라
System.out.printf("%,+.2f", 100000.0/3.0);
// +33,333.33
  • String format
    String 객체로 원하는 문자열을 생성
String message = String.format("Hello, %s. Next year, you'll be %d\n",name,age);

1.7 Control Flow

if, for, while과 같은 것을 사용하는 것
결론은 C/C++과 동일하다.

  • if- else if - if 문
if(조건문){
	(code)
}else if(조건문){
	(code)
}else{
	(code)
}

ex> + Random() 사용방법

class If1 {
	public static void main(String[] args){
		// n : -5 ~ 5 random number(integer)
        //Math 클래스의 함수를 사용하여 [0,1) 사이의 값을 반환
		int n = (int)( 11*Math.random() ) - 5;
		System.out.println("Random number : " + n);
        
		if (n > 0) System.out.println("positive");
		else System.out.println("0 or negative");
	}
} 
  • for 문
for(i =1;i<10;++i) <statement>
  • while 문
while(조건){
	코드
}
  • do-while 문
do{
	코드
}while(조건);
  • break 문
for (i =1;;++i){
	break;
}
  • continue 문
while(sum<goal){
	if(n<0) continue;
}
  • switch 문
switch(choice){
	case 1:
    코드
    break;
    
    case 2:
    코드
    break;
    
    default:
    코드
    break;
}
profile
신촌거지출신개발자(시리즈 부분에 목차가 나옵니다.)

0개의 댓글