카테고리 없음

19-03-13_TIL

Doohwancho 2019. 3. 13. 14:45
package Java_book;
// 클래스의 이름은 항상 대문자로 한다.
public class HelloWorld {
//Q1. why have to add static in order to print this var?
static float pi = 3.14f;
static double rate = 1.618d;
//trial01. 타입의 불일치
//타입이 달라도 저장범위가 넓은 타입에 좁은 타입의 값을 저장하는 것이 허용된다.
static int i = 'A';
static long l = 123;
static double d = 3.14f;
//trial02. colons
static char ch = 'J';
static String name = "java";
//static char ch1 = "J"; //char일 때 ""를 사용하면 에러난다.
//static char ch2 = ''; //char일때 ''안 최소 한가지 문자열 필요. space도 가능.
static char ch3 = ' ';
//trial03. printf()
//println()은 변수의 값을 그대로 출력하므로, 값을 변환하지 않고는 다른형식 출력 불가능 하다.
//이럴 때ㅐ printf()를 사용하면 된다.
static int age = 27;
//trial04. string manipulation
static String url = "www.codechobo.com";
public static void main(String[] args) {
System.out.println("Hello, world!");
System.out.println(pi);
System.out.println(rate);
//why can't i print(pi,rate)? //reference to trial03
//System.out.println(pi,rate);
//trial01. 타입의 불일치
System.out.println(i);
System.out.println(l);
System.out.println(d);
//trial02. colons
System.out.println(ch);
System.out.println(name);
//trial03. printf()
System.out.printf("age:%d", age);
System.out.printf("%f%n + %f%n", pi, rate); //%n이 ""안에 있으면 엔터를 의미
//trial04. string manipulation
System.out.printf("[%s]%n", url);
System.out.printf("[%20s]%n", url);
System.out.printf("[%-20s]%n",url);
System.out.printf("[%.8s]%n",url); //앞에서 8개만 끊는다.

결과창

Hello, world!
3.14
1.618
65
123
3.140000104904175
J
java
age:273.140000
+ 1.618000
[www.codechobo.com]
[ www.codechobo.com]
[www.codechobo.com ]
[www.code]




/* Scanner란
* 화면에서부터 입력받기
*/
package Java_book;
import java.util.*; //scanner사용을 위해 추가
public class ScannerEx {
public static void main(String[] args) {
//처음엔 class_name과 file_name이 Scanner였다.
//그래서 Scanner type으로 선언했는데, 원래 Scanner class가 아닌, 이 파일을 참조해서 에러가 났었다.
Scanner scanner = new Scanner(System.in); //scanner 클래스의 객체를 생성
System.out.println("두자리 정수를 하나 입력해주세요.>");
String input = scanner.nextLine(); //nextLine()메서드는 입력하면 문자열로 반환한다.
int num = Integer.parseInt(input); //입력받을 값을 int로 변환
//float f = Integer.parseFloat(input);
System.out.println("입력내용 : "+input);
System.out.printf("num=%d%n",num);
}
}
결과값
두자리 정수를 하나 입력해주세요.>
10
입력내용 : 10
num=10