'전체 글'에 해당되는 글 384건
<table> ; 표의 시작
<table border="숫자"> ; 테두리의 굵기 지정 *border보단 css로 꾸미는 것이 이쁘다...!
<thead> ; table head ; 안묶어도 브라우저가 자동설정한다.
<tbody> ; table body ; 안묶어도 브라우저가 자동설정한다.
<tr> ; table row ; 같은 행으로 묶어주는 기능 </tr>
<th> ; 데이터들의 제목을 진하게 표시 </th>
<td> ; table data ; 항목을 묶어주는 기능 </td>
<tfoot> ; 묶인 영역은 자동으로 맨 아래 행으로 내려감
<td rowspan ="숫자"> ; 숫자에 쓰인 행(row)만큼 병합됨. 숫자-1 만큼 해당 행 삭제해야함.
<td colspan ="숫자"> ; 숫자에 쓰인 열(column)만큼 병합됨. 숫자-1 만큼 해당 열 삭제해야함.
'HTML & CSS' 카테고리의 다른 글
정보로서의 HTML (0) | 2019.07.02 |
---|---|
입력양식 - form (0) | 2019.06.27 |
부록 : 코드의 힘 (0) | 2019.06.23 |
서버와 클라이언트 (0) | 2019.06.21 |
부모 자식과 목록 (0) | 2019.06.19 |
charAt (문장중에 인덱스 위치에 해당되는 문자 추출하기)
subString ( 원하는 범위만큼 문자열 잘라내기 )
split ( 주어진 문자로 분리하여 배열에 저장 )
indexOf (해당 문자열에서 특정 문자의 위치를 찾아 리턴한다.)
'Java' 카테고리의 다른 글
Java - Overloading, 가변인자, 배열, 메소드 (0) | 2019.07.08 |
---|---|
은행계좌시스템 (0) | 2019.07.01 |
Collections Framework (0) | 2019.06.15 |
제네릭 (0) | 2019.06.15 |
참조 (0) | 2019.06.14 |
import java.util.Scanner;
public class 과제0627 {
public static void main(String[] args) {
//과제1> 구구단을 출력하되, 곱하는 수가 단보다 커지면 중지합니다.(ex. 2단 : 2x2까지만 출력)
// 1
// 2 4
// 3 6 9
// 4 8 12 16
// 5 10 15 20 25
// 6 12 18 24 30 36
// 7 14 21 28 35 42 48
// 8 16 24 32 40 48 56 64
// 9 18 27 36 45 54 63 72 81
for(int i = 1; i<=9; i++) { // i : 단=행(row)
for(int j = 1; j<=i ; j++) { // j: 곱하는 수
System.out.print(i*j);
System.out.print(" ");
}
System.out.println(); //줄바꿈 의미
}
//과제2> 다음과 같이 출력하세요.
// *******
// *****
// ***
// *
for(int i = 4; i>=1; i--) {
for(int j = i ; j<=3 ; j++) {
System.out.print(" ");
}
for(int k = 1 ; k<=2*i-1 ; k++) {
System.out.print("*");
}
System.out.println();
}
//강사님 풀이
for(int i = 0; i<4; i++) { // 바깥부분 반복
for(int j = 0; j<i; j++) { //바깥 블랭크(blank) = null = " "
System.out.print(" ");
}
for(int k = 0 ; k<(5-i)*2-3 ; k++) { // 공식(rule)을 생각해BOA요.
System.out.print("*");
}
System.out.println(); // 줄바꿈
}
//과제3> 1~100사이의 연산의 합계를 구하세요. (숫자는 증가, 연산자는 덧셈,뺄셈 반복)
// 1-2+3-4+5-6+7-8+.......100 = ?
// 3가지 이상의 방법을 사용하여 풀어보세요.
//1. for문
int sum = 0;
for(int i = 1; i<=100; i++) {
if(i%2 == 1)
sum+=i;
else
sum-=i;
}System.out.println("for문 : " + sum); // -50
//강사님 풀이1 - 문제에 대한 흐름, 규칙을 잘 찾아내는 것이 중요하다.
int sum = 0, odd = 0, even=0;
for(int i = 1; i<=100; i++) {
if(i%2 == 1) // 홀수연산
odd+=i;
else
even-=i; // 짝수연산
}System.out.println("for문 : " + (odd + even)); // -50
//강사님 풀이2 - true, false이용
int i, sum=0, sw=1;//sw=true, sw=false
for(i=1; i<=100; i++) {
if(sw ==1) { // 홀수연산
sum+=i;
sw=0; //false
}else {
sum-=i; // 짝수연산
sw=1; // true
}
}System.out.println("true, false이용 : " + sum); // -50
//강사님 풀이3 - 부호변환(일반 수학적용)
int sum = 0, i, p=1; //p:부호변환용 기호(+,-) 변수
for(i=1; i<=100; i++) {
sum+=i * p;// sum = sum + (i * p); //p값은 변동되지 않고, 아래 변환지점에서 변환된다.
p*=-1;//p = p * -1; // 부호변환 지점(부분)
}
System.out.println("부호변환이용 : " + sum); // -50
//강사님 풀이4
int sum = 0, i;
for(i=1; i<=100; i++) {
if(i/2 != i/2.0) //0.0
sum+=i; //0 not equal 0.5 = 1, 1 1.5 =3
else //2 2 2.0=4
sum-=i;
}System.out.println("4번방법 : " + sum); // -50
//2. while문
int i = 1, sum = 0;
while(i<=100){
if(i%2 == 1)
sum+=i;
else
sum-=i;
i++;
}System.out.println("while문 : " + sum); // -50
//3. do ~ while문
int sum=0, i = 1;
do{
if(i%2 == 1)
sum+=i;
else
sum-=i;
i++;
}while(i<=100);
System.out.println("do ~ while문 :" + sum); // -50
//과제4> 반지름을 입력 받아서, 원의 넓이와 둘레를 구하여 출력하세요.
// 계속하려면 yes를 입력하고, no이면 중단합니다.
Scanner sc = new Scanner(System.in);
float p = 3.14f;
while(true) {
System.out.println("반지름을 입력하세요.");
float r = sc.nextInt();
double area = p * r * Math.pow(r,2);
double girth = 2 * p * r;
System.out.println("원의 넓이는 " + area + "원의 둘레는" + girth +"입니다.");
System.out.println("계속하려면 yes를, 중단하시려면 no를 입력하세요.");
String ans = sc.next();
if(ans.equals("yes")) {
continue;
}else if(ans.equals("no")) {
System.out.println("프로그램을 종료합니다..");
System.exit(0);
}
}
//강사님 풀이
double radian;
for( ; true ; ) {
System.out.println("반지름을 입력해 주세요.");
BufferedReader br2 = new BufferedReader(new InputStreamReader(System.in));
radian = Double.parseDouble((br2.readLine()));//
double d = radian * radian * 3.14159267;//원의 넓이
double e = radian * 2 * 3.14159267;//원의 둘레
System.out.println("원의 넓이 = " + d);
System.out.println("원의 둘레 = " + e);
System.out.println("계속하시겠습니까? (yes:계속, no:중단");
String str = br2.readLine();
if(!str.equals("yes")) {
System.out.println("프로그램이 정상적으로 종료되었습니다.");
break;
}
}
}
}
주요내용 : switch~case 마무리, 반복문(for, while, do ~ while) - 구구단출력, 별찍기
//switch ~ case
//다음과 같이 주민등록번호가 존재합니다. 123456-1234567
//이 주민번호를 가지고 남성인지, 여성인지 판별하여 출력합니다.
//1, 3 : 남성, 2,4 : 여성, 1900년대 :1,2 2000년대 : 3,4
String juminbunho = "123456-4234567";
char gubun = juminbunho.charAt(7);
if(gubun == '1' || gubun == '3') {
System.out.println("남성입니다.");
}else {
System.out.println("여성입니다.");
}
//위의 소스를 switch~case 버전으로 변경하세요.
String juminbunho = "123456-5234567";
char gubun = juminbunho.charAt(7);
switch(gubun) {
case '1': //case 붙여쓰면 바로 아래 나오는 거에 같이 해당된다고 생각하면 됨.
case '3':
System.out.println("남성입니다.");
break;
case '2':
case '4':
System.out.println("여성입니다.");
break;
default :
System.out.println("잘못입력하셨습니다.");
break;
}
//문제] 임의의 수 100이 주어집니다.
//다음과 같은 조건을 만족하는 값을 출력하세요.
//1. 7로 나눌대, 나머지가 1인 수
//2. 7로 나눌대, 나머지가 2 또는 3인 수
//3. 7로 나눌대, 나머지가 4 또는 5인 수
//4. 7로 나눌대, 나머지가 6인 수
//5. 7로 나누어 떨어지는 수.
//if문
int x = 100;
if(x%7==1) {
System.out.println("x[" + x + "]는 나눌 때, 나머지가 1인 수");
}else if(x%7==2 || x%7==3) {
System.out.println("x[" + x + "]는 나눌 때, 나머지가 2 또는 3인 수");
}else if(x%7==4 || x%7==5) {
System.out.println("x[" + x + "]는 나눌 때, 나머지가 4 또는 5인 수");
}else if(x%7==6) {
System.out.println("x[" + x + "]는 나눌 때, 나머지가 6인 수");
}else if(x%7==0){
System.out.println("x[" + x + "]는 나누어 떨어지는 수");
}
//switch문
int x = 777;
switch(x%7) {
case 1 :
System.out.println("x[" + x + "]는 나눌 때, 나머지가 1인 수");
break;
case 2 :
case 3 :
System.out.println("x[" + x + "]는 나눌 때, 나머지가 2 또는 3인 수");
break;
case 4 :
case 5 :
System.out.println("x[" + x + "]는 나눌 때, 나머지가 4 또는 5인 수");
break;
case 6 :
System.out.println("x[" + x + "]는 나눌 때, 나머지가 6인 수");
break;
default :
System.out.println("x[" + x + "]는 나눌 때, 나누어 떨어지는 수");
break;
}
--------------------------------------------------------------------------
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.text.DecimalFormat;
import java.util.Scanner;
//반복문 : 조건문이 처리하고자하는 내용을 반복.
//종류 : for, while, do ~ while
// for의 형식
// for(초기값; 조건식; 증감식){
// ..........;
// }
// while(조건식){ // 먼저 조건식을 체크.
// .....;
// }
// do{ // 적어도 한번은 실행합니다.
// ......;
// while(조건식);
public class JavaTwo {
public static void main(String[] args) throws NumberFormatException, IOException {
//1 ~ 100 사이의 합계를 구하세요.
// int i, sum = 0; //매번 초기화해야 오류가 안난다.
//1. for문
// 초기값 조건식 증감식
for(i = 0; i<=100; i++) { // i++ 는 i+=1 와 i=i+1 과 같다.
sum+=i;
}
System.out.println("for문 : 1 ~ 100 사이의 합은 : " + sum); //5050
//2. while문
while(i<=100) {
sum+=i;
i++;
}
System.out.println("while문 : 1 ~ 100 사이의 합은 : " + sum); // 5050
//3. do ~ while문
int sum2=0, i2 = 0;
do{
sum2+=i2;
i2++;
}while(i2<=100);
System.out.println("do ~ while문 : 1 ~ 100 사이의 합은 : " + sum2); //5050
//문제] 1 ~ 100 사이의 수 중에서 홀수의 합을 구하여 출력하세요.
//단, for, while, do~while을 사용합니다.
//1. for문
for(i = 0; i<=100; i++) {
if(i%2 == 0)
continue; //분기문 : 건너뛰기, skip
sum+=i;
}System.out.println("for문 : 1 ~ 100 사이의 수 중에서 홀수의 합은 : " + sum); //2500
//2. while문
while(i<=100){
if(i%2 == 0)
continue;
sum+=i;
}System.out.println("while문 : 1 ~ 100 사이의 수 중에서 홀수의 합은 : " + sum); //2500
//3. do ~ while문
int sum2=0, i2 = 0;
do{
if(i2%2 == 1) {
sum2+=i2;
}
i2++;
}while(i2<=100);
System.out.println("do ~ while문 : 1 ~ 100 사이의 수 중에서 홀수의 합은 : " + sum2); //2500
//문제] 1 ~ 100 사이의 수 중에서 짝수의 합을 구하여 출력하세요.
//단, for, while, do~while을 사용합니다.
//1. for문
for(i = 0; i<=100; i++) {
if(i%2 == 0)
sum+=i;
}System.out.println("for문 : 1 ~ 100 사이의 수 중에서 짝수의 합은 : " + sum); //2550
//2. while문
while(i<=100){
if(i%2 == 0)
sum+=i;
}System.out.println("while문 : 1 ~ 100 사이의 수 중에서 짝수의 합은 : " + sum); //2550
//3. do ~ while문
int sum2=0, i2 = 0;
do{
if(i2%2 == 0) {
sum2+=i2;
}
i2++;
}while(i2<=100);
System.out.println("do ~ while문 : 1 ~ 100 사이의 수 중에서 짝수의 합은 : " + sum2); //2550
//감소하기 : 카운트다운
for(int i = 100; i>0; i--) {
System.out.println(i);
}
int i = 100; //초기값을 밖에서 선언
for( ; ; ) { // 초기값, 증감식 생략가능.
if(i>0) { // 조건식 for문 안쪽에서 선언.
System.out.println(i);
i--; // 증감식 for문 마지막에 선언.
}
}
int count = 0;
for(int i = 100; i>=0; i-=10) {
System.out.println(i);
count+=1;
}
System.out.println("갯수는 " + count); // 갯수출력(11)
//1~100사이의 수 중에서 5의 배수의 합을 구하고 카운트하여 출력하세요.
//1-1. for문(if문)
int i, sum = 0;
for(i = 1; i<=100; i++) {
if(i%5 ==0) {
sum+=i;
}
}
System.out.println("for문 : 1 ~ 100 사이의 수중에서 5의 배수의 합은 : " + sum); // 1050
//1-2. for문(if문 안쓰고 5의 배수로 반복.)
int i, sum = 0;
for(i = 5; i<=100; i+=5) { //
sum+=i;
}
System.out.println("for문 : 1 ~ 100 사이의 수중에서 5의 배수의 합은 : " + sum); // 1050
//2. while문
while(i<=100) {
sum+=i;
i+=5;
}
System.out.println("while문 : 1 ~ 100 사이의 수중에서 5의 배수의 합은 : " + sum); // 1050
//3. do ~ while문
int sum2=0, i2 = 0;
do{
sum2+=i2;
i2+=5;
}while(i2<=100);
System.out.println("do ~ while문 : 1 ~ 100 사이의 수중에서 5의 배수의 합은 : " + sum2); //1050
//문제] 1부터 1씩 증가하여 최초로 합이 3000이 넘는 정수의 값은 얼마인가?
//1.for문
int i, sum = 0;
for(i = 1; ; i++) {
sum+=i;
if(sum >= 3000) {
System.out.println(i); // 77
System.out.println(sum); // 3003
break;
}
}
//2. while문
int i = 0 , sum = 0;
while(sum<=3000) {
i++;
sum+=i;
}
System.out.println(i); // 77
System.out.println(sum); // 3003
//3. do ~ while문
int sum2=0, i2 = 0;
do{
i2++;
sum2+=i2;
}while(sum2<=3000);
System.out.println(i2); // 77
System.out.println(sum2); // 3003
//문제] 구구단을 출력합니다. 2단~ 19단
//1. for문
int i = 1, j = 1;
for(i=2;i<=19;i++) {
for(j=1;j<=9;j++) {
System.out.println(i + "x" + j + "=" +i*j);
}
}
//2. while문
int i = 2, j = 1;
while(i<=19) {
while(j<=9) {
System.out.println(i + "x" + j + "=" +i*j);
j++;
}
i++;
j=1; //초기화!!(구구단이므로)
}
//문제] 출력을 원하는 단을 출력하도록 프로그래밍 하세요.
Scanner sc = new Scanner(System.in);
System.out.println("출력하고자 하는 구구단 단수를 입력하세요.");
int i = sc.nextInt();
int j = 1;
for(j=1; j<=9;j++) {
System.out.println(i + "x" + j + "=" +i*j);
}
//강사님 풀이
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("출력하고자 하는 구구단 단수를 입력하세요.");
int gugu = Integer.parseInt((br.readLine()));
System.out.println("***" + gugu + "단***");
for(int j=1; j<=9;j++) {
System.out.println(gugu + "x" + j + "=" +(gugu*j));
}
//문제] 구구단 중에서 홀수단을 출력하되, 단의 수만큼 출력되도록 합니다.
for(int i=1;i<=19;i+=2) { //i의 값을 따로 2n-1 식으로 변수를 주지 않고, 증가값을 홀수값이 되도록 증가하도록 설정.
for(int j=1;j<=i;j++) {
System.out.println(i + "x" + j + "=" +i*j);
}
System.out.println();
}
//문제] 별찍기 - #을 10개씩 3줄에 출력하세요.
//1. 노가다방법
for(int i = 0; i<10; i++) {
System.out.print("#");
}
System.out.println();
for(int i = 0; i<10; i++) {
System.out.print("#");
}
System.out.println();
for(int i = 0; i<10; i++) {
System.out.print("#");
}
System.out.println();
//2. 좋은 방법
for(int i = 0; i<3; i++) {
for(int j = 0 ; j<10 ; j++) {
System.out.print("#");
}
System.out.println();
}
//문제] 별찍기 - #을 5행으로 3개씩 출력하세요.
for(int i = 0; i<5; i++) {
for(int j = 0 ; j<3 ; j++) {
System.out.print("#");
}
System.out.println();
}
//문제] 다음과 같이 출력 되도록 합니다.
// 28 27 26
// 25 24 23
// 22 21 20
int num = 28;
for(int i = 0; i<3; i++) {
for(int j = 0 ; j<3 ; j++) {
System.out.print(num + "\t"); // \t : tab키
num--;
}
System.out.println();
}
//문제] 다음과 같이 출력 되도록 합니다.
// 1 2 3 4 5
// 6 7 8 9 10
// 11 12 13 14 15
int num = 1;
for(int i = 0; i<3; i++) {
for(int j = 0 ; j<5 ; j++) {
System.out.print(num + "\t");
num++;
}
System.out.println();
}
//문제] 다음과 같이 출력되도록 합니다.
// 12345
// 12345
// 12345
// 12345
// 12345
for(int i = 0; i<5; i++) {
for(int j = 1 ; j<=5 ; j++) {
System.out.print(j);
}
System.out.println();
}
System.out.println();
//문제] 다음과 같이 출력되도록 합니다.
// *
// **
// ***
// ****
// *****
for(int i = 1; i<=5; i++) {
for(int j = 1 ; j<=i ; j++) {
System.out.print("*");
}
System.out.println();
}
System.out.println();
//문제] 다음과 같이 출력되도록 합니다.
// 1
// 12
// 123
// 1234
// 12345
for(int i = 1; i<=5; i++) {
for(int j = 1 ; j<=i ; j++) {
System.out.print(j);
}
System.out.println();
}
System.out.println();
//문제] 다음과 같이 출력되도록 합니다.
// *****
// ****
// ***
// **
// *
for(int i = 1; i<=5; i++) {
for(int j = 5 ; j>=i ; j--) {
System.out.print("*");
}
System.out.println();
}
System.out.println();
//문제] 다음과 같이 출력되도록 합니다.
// *****
// ****
// ***
// **
// *
for(int i = 5; i>=1; i--) {
for(int j = 1; j<=5-i; j++) {
System.out.print(" ");
}
for(int k = 1; k<=i; k++) {
System.out.print("*");
}
System.out.println();
}
System.out.println();
//문제] 다음과 같이 출력되도록 합니다.
// 12345
// 1234
// 123
// 12
// 1
for(int i = 5; i>=1; i--) {
for(int j = 1; j<=5-i; j++) {
System.out.print(" ");
}
for(int k = 1; k<=i; k++) {
System.out.print(k);
}
System.out.println();
}
System.out.println();
//문제] 다음과 같이 출력되도록 합니다.
// 1 2 3 4 5
// 1 2 3 4
// 1 2 3
// 1 2
// 1
for(int i = 5; i>=1; i--) {
for(int j = 1 ; j<=i ; j++) {
System.out.print(j + " ");
}
System.out.println();
}
System.out.println();
//문제] 다음과 같이 출력되도록 합니다.
// 1
// 1 2
// 1 2 3
// 1 2 3 4
//1 2 3 4 5
for(int i = 1; i<=5; i++) {
for(int j = 1 ; j<=5-i ; j++) {
System.out.print(" ");
}
for(int k = 1 ; k<=i ; k++) {
System.out.print(k + " ");
}
System.out.println();
}
System.out.println();
//문제] 다음과 같이 출력되도록 합니다.
//1 2 3 4 5
// 1 2 3 4
// 1 2 3
// 1 2
// 1
for(int i = 5; i>=1; i--) {
for(int j = 1 ; j<=5-i ; j++) {
System.out.print(" ");
}
for(int k = 1 ; k<=i ; k++) {
System.out.print(k + " ");
}
System.out.println();
}
System.out.println();
//문제] 다음과 같은 처리를 하도록 프로그램을 작성하세요.
//-----------------------
//1.예금 2.출금 3.잔액조회 4.종료
//-----------------------
//강사님 풀이법
String str;
String balance = null;
int total = 0;
boolean run = true;
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
while(run) {
System.out.println("----------------------------");
System.out.println("1.예금 | 2.출금 | 3.잔고 | 4.종료 ");
System.out.println("----------------------------");
System.out.println("선택>> ");
str = br.readLine();
switch(str) {
case "1":
System.out.println("예금액>>");
balance = br.readLine();
total += Integer.parseInt(balance);
break;
case "2":
System.out.println("출금액>>");
balance = br.readLine();
total -= Integer.parseInt(balance);
break;
case "3":
System.out.println("잔고>>");
System.out.println(total);
break;
case "4":
run = false;
System.out.println("프로그램을 종료합니다.");
break;
}
System.out.println();
}
}
}
import java.util.Scanner;
public class 과제0626 {
public static void main(String[] args) {
//과제1] 이름과 국어, 영어, 수학 점수를 입력받아서 총점, 평균, 학점을 구하세요.(처리는 if문 이용.)
Scanner sc = new Scanner(System.in);
System.out.println("이름을 입력하세요.");
String name = sc.next();
System.out.println("국어 점수를 입력하세요.");
int kor = sc.nextInt();
System.out.println("영어 점수를 입력하세요.");
int eng = sc.nextInt();
System.out.println("수학 점수를 입력하세요.");
int math = sc.nextInt();
int sum = kor + eng + math;
double avg = sum / 3.0; // 소수점이므로 double 을 썻다.
char grade;
if(avg>=90) {grade = 'A';
} else if(avg>=80) {grade = 'B';
} else if(avg>=70) {grade = 'C';
} else if(avg>=60) {grade = 'D';
} else if(avg>=50) {grade = 'E';
} else {grade = 'F';}
System.out.println(name + "님의 총점은 " + sum + "점. 평균은 " + avg + "점. 학점은 " + grade + "등급 입니다.");
//switch문 이용
int aver = (int)avg;
switch(aver/10) {
case 10:
case 9 :
grade ='A';
break;
case 8 :
grade ='B';
break;
case 7 :
grade ='C';
break;
case 6 :
grade ='D';
break;
default :
grade = 'F';
}
System.out.println(name + "님의 총점은 " + sum + "점. 평균은 " + avg + "점. 학점은 " + avg + "등급 입니다.");
//[과제2] equals, if 이용, 숫자 2개를 입력 받아서 연산자에 의하여 처리 되도록 합니다.
//입력 양식> 30 50 + => 80, 40 20 - => 20 (연산자도 입력을 받아서 처리 : equals사용)
Scanner sc = new Scanner(System.in);
System.out.println("숫자를 입력하세요.");
int x = sc.nextInt();
System.out.println("숫자를 입력하세요.");
int y = sc.nextInt();
System.out.println("연산자를 입력하세요.");
String oper = sc.next();
if(oper.equals("+")) {System.out.println(x + y);
}
else if(oper.equals("-")) {System.out.println(x - y);
}
else if(oper.equals("*")) {System.out.println(x * y);
}
else if(oper.equals("/")) {System.out.println(x / y);
}
else if(oper.equals("%")) {System.out.println(x % y);
}
else{System.out.println("연산에 이상이 발생하였습니다!");
//[과제3] 음식점의 메뉴가 다양하게 전시되어 있습니다.
//1.피자 2.스파게티 3.햄버거 4.스프 5.토마토가 존재 합니다.
//피자 가격은 8600원이고, 스파게티는 15000원, 햄버거는 10만원, 스프는 5천원, 토마토는 3500원 입니다.
//if문으로 작성하고, 이를 switch ~ case문으로 옮겨보세요.
//=============================
//메 뉴 가 격
//=============================
//1.피자 8,600
//2.스파게티 15,000
//3.햄버거 100,000
//4.스프 5,000
//5.토마토 3,500
//6.종료
//=============================
//
//다음 메뉴중에서 고르세요.
//1
//주문할 피자의 갯수를 입력하세요: 3
//8600 * 3 = 25,800원 입니다.
//6
//프로그램이 종료되었습니다.
//if문
DecimalFormat df = new DecimalFormat("##,###"); // 숫자표시 형식 지정!!!!
Scanner sc = new Scanner(System.in);
while(true) {
System.out.println("=============================");
System.out.println(" 메 뉴 가 격 ");
System.out.println("1. 피자 8,600 ");
System.out.println("2. 스파게티 15,000 ");
System.out.println("3. 햄버거 100,000 ");
System.out.println("4. 스프 5,000 ");
System.out.println("5. 토마토 3,500 ");
System.out.println("6. 종료 ");
System.out.println("=============================");
System.out.print("다음 메뉴 중에서 고르세요 : ");
int choice = sc.nextInt();
if (choice == 6) {
System.out.println("프로그램이 종료되었습니다.");
System.exit(0); // 프로그램 종료
break;
} else if (choice == 1) {
System.out.println("주문할 피자의 갯수를 입력하세요.");
int menu = sc.nextInt();
String dfSu = df.format(menu*8600); // 형식지정!!!, 가격변동이 있을경우 변수를 위로 올려서 코딩짜는게 낫다!!!
System.out.println("8,600원 * " + menu + "개 =" + dfSu + "원 입니다.");
break;
} else if (choice == 2) {
System.out.println("주문할 스파게티의 갯수를 입력하세요.");
int menu = sc.nextInt();
String dfSu = df.format(menu*15000);
System.out.println("15,000원 * " + menu + "개 =" + dfSu + "원 입니다.");
break;
} else if (choice == 3) {
System.out.println("주문할 햄버거의 갯수를 입력하세요.");
int menu = sc.nextInt();
String dfSu = df.format(menu*100000);
System.out.println("100,000원 * " + menu + "개 =" + dfSu + "원 입니다.");
break;
} else if (choice == 4) {
System.out.println("주문할 스프의 갯수를 입력하세요.");
int menu = sc.nextInt();
String dfSu = df.format(menu*5000);
System.out.println("5,000원 * " + menu + "개 =" + dfSu + "원 입니다.");
break;
} else if (choice == 5) {
System.out.println("주문할 토마토의 갯수를 입력하세요.");
int menu = sc.nextInt();
String dfSu = df.format(menu*3500);
System.out.println("3,500원 * " + menu + "개 =" + dfSu + "원 입니다.");
break;
} else {
System.out.println("잘못 누르셨습니다.");
}
}
//switch문
DecimalFormat df = new DecimalFormat("##,###");
int pizza = 8600;
int spa = 15000;
int ham = 100000;
int soup = 5000;
int toma = 3500; // 유지보수 및 가격변동을 대비해 변수를 위로 올려서 코딩을 짰다.
Scanner sc = new Scanner(System.in);
while(true) {
System.out.println("=============================");
System.out.println(" 메 뉴 가 격 ");
System.out.println("1. 피자 8,600 ");
System.out.println("2. 스파게티 15,000 ");
System.out.println("3. 햄버거 100,000 ");
System.out.println("4. 스프 5,000 ");
System.out.println("5. 토마토 3,500 ");
System.out.println("6. 종료 ");
System.out.println("=============================");
System.out.print("다음 메뉴 중에서 고르세요 : ");
int choice = sc.nextInt();
switch (choice) {
case 6 :
System.out.println("프로그램이 종료되었습니다.");
System.exit(0);
break;
case 1 :
System.out.println("주문할 피자의 갯수를 입력하세요.");
int menu = sc.nextInt();
String dfSu = df.format(menu*pizza);
System.out.println("8,600원 * " + menu + "개 =" + dfSu + "원 입니다.");
break;
case 2 :
System.out.println("주문할 스파게티의 갯수를 입력하세요.");
int menu2 = sc.nextInt();
String dfSu2 = df.format(menu2*spa);
System.out.println("15,000원 * " + menu2 + "개 =" + dfSu2 + "원 입니다.");
break;
case 3 :
System.out.println("주문할 햄버거의 갯수를 입력하세요.");
int menu3 = sc.nextInt();
String dfSu3 = df.format(menu3*ham);
System.out.println("100,000원 * " + menu3 + "개 =" + dfSu3 + "원 입니다.");
break;
case 4 :
System.out.println("주문할 스프의 갯수를 입력하세요.");
int menu4 = sc.nextInt();
String dfSu4 = df.format(menu4*soup);
System.out.println("5,000원 * " + menu4 + "개 =" + dfSu4 + "원 입니다.");
break;
case 5 :
System.out.println("주문할 토마토의 갯수를 입력하세요.");
int menu5 = sc.nextInt();
String dfSu5 = df.format(menu5*toma);
System.out.println("3,500원 * " + menu5 + "개 =" + dfSu5 + "원 입니다.");
break;
default :
System.out.println("잘못 누르셨습니다.");
break;
}
}
}
}
'Bitcamp > BITCAMP - Java' 카테고리의 다른 글
4일차 - 과제 (0) | 2019.06.27 |
---|---|
4일차 (0) | 2019.06.27 |
3일차 (0) | 2019.06.26 |
2일차 - 과제 (0) | 2019.06.26 |
2일차 - GUISample1 (0) | 2019.06.25 |
주요내용 : 한글자입력, ASCII코드, 제어문자, 조건문과 그에 따른 예제, 난수발생클래스, 배수 구하기
import java.io.IOException;
import java.util.Random;
import java.util.Scanner;
public class printfTest {
public static void main(String[] args) throws IOException{
// print vs. println vs. printf
// print : 출력 후 가만히 있음.
// println : 출력 후 줄바꿈
// printf : "형식지정자"에 %와 영문자를 조합해서 다양한 자료타입을 출력.(소수점이하 자리를 정밀하게 쓸수있다.)
// : %5d : 5자리(왼쪽) 확보후 출력
// : %-5d : 5자리(오른쪽) 확보 후 출력
// : %05d : 왼쪽에 생긴 빈공간을 0으로 채움
int su = 12345;
System.out.printf("\n %8d\n", su);
System.out.printf("\n %-8d\n", su);
System.out.printf("\n %08d\n", su);
// 한글자 입력 연습
// 한글자 입력 - System.in.read(); 를 활용
// - java.io 패키지의 InputStream 클래스이며, 이 클래스내의 모든것을 사용 가능하며, 아스키코드 값으로 입력을 받는다.
// - int a = System.in.read();
// System.out.println("입력한 내용은 =“ + a); A를 입력하면 65가 나오게 된다.
// - 만약 입력한 내용 그대로 나오게 하려면
// char a = (char)Sytem.in.read(); 이렇게 해줘야 한다.
// - 숫자일 경우에는
// int a = System.in.read() - 48; 또는
// int a = System.in.read() - '0'을 해준다
//
// ASCII CODE 암기할것.
// - 숫자: 0 ~ 9 => 48-57
// - 대문자: A ~ Z => 65-90
// - 소문자: a ~ z => 97-122
int ken = 0;
System.out.print("키보드로부터 문자 입력 요망: ");
char art = (char)System.in.read(); // A -> 문자처리
System.in.read();
System.in.read();
System.out.println("입력한 문자 : " + art); // A
System.out.print("키보드로부터 입력 요망 : ");
ken = System.in.read(); //A, 예외처리부분, 숫자처리
System.out.print("입력한 문자의 10진수는: " + ken); // 65
// 0~9 사이의 숫자 3개를 이용하여 합계를 구하는 프로그램을 작성하세요.
int x, y, z, sum;
System.out.println("X의 값을 한자리로 입력해주세요");
x = System.in.read() - 48;
System.in.read(); // enter의 기능
System.in.read();
System.out.println("X의 값을 한자리로 입력해주세요");
y = System.in.read() - '0';
System.in.read(); // enter의 기능
System.in.read();
System.out.println("X의 값을 한자리로 입력해주세요");
z = System.in.read() - 48;
System.in.read(); // enter의 기능
System.in.read();
sum = x + y + z;
System.out.println("합계는 = " + sum);
//제어문자
System.out.println("새 줄 (New line)\t\\n\t" + (int) '\n'); // 역슬래쉬 뒤에 출력되는 값은 컴퓨터의 코드값임.
System.out.println("탭 (Tab)\t\\t\t" + (int) '\t');
System.out.println("백스페이스 (Backspace)\t\\b\t" + (int) '\b');
System.out.println("단일 인용부호 (Single Quote)\t\\'\t" + (int) '\'');
System.out.println("이중 인용부호 (Double Quote)\t\\\"\t" + (int) '\"');
System.out.println("백슬래시 (Backslash)\t\\\\\t" + (int) '\\');
System.out.println("널 문자 (null)\t\\0\t" + (int) '\0');
//형변환 - 메모리 낭비되는 경우
float x = 100.678f; //4바이트 메모리
double y = (double)x; //8바이트 메모리, 메모리 낭비됨.
//변수와 블록의 범위 실습
{//시작 block D
int d= 10;
{//시작 block C
int c = 20;
{//시작 blcok B
int b = 30;
{//시작 blcok A
int a = 40;
//a,b,c,d 모두 사용가능
a = 200;
b = 1000;
c = 2000;
d = 50;
System.out.println("1 : " +a+" "+b+" "+c+" "+d);
//System.out.printf("1 :%d %d %d %d\n",a,b,c,d);
}// end A
b = 200;
c = 300;
d = 60;
//b,c,d가 살수 있다.
System.out.println("2 : "+b+" "+c+" "+d);
//System.out.printf("2 : %d %d %d\n",b,c,d);
}// end B
c = 300;
d = 70;
//c,d가 살 수 있다.
System.out.println("3 : "+c+" "+d);
//System.out.printf("3 : %d %d\n",c,d);
}// end C
d=80; //d만 살수있다.
System.out.println("4 : " +d);
//System.out.printf("4 : %d\n",d);
}
//3장. 연산자
// int x = 300;
// int y = 500;
// int sum = x + y;
/* int : 정수형 데이터
* sum = x + y;
* operand operator operand
* (연산의 대상) (연산자) (연산의 대상)
*
*/
// + : 덧셈, 연결연산자("nn" + "입니다.");
// - : 뺄셈, 부호변환(-- : +, ...)
// 지수승 : System.out.println("y^3 =" + (y*y*y)); // y의3승표현
// 산술연산자와 ASCII 코드
char c1 = 'A' + 1; // 65 + 1 = 66(B)
char c2 = 'A';
int c3 = c2 + 1; // char : -128 ~ 127
// char c3 = c2 + 1; // Error
System.out.println("c1: " + c1);
System.out.println("c2: " + c2);
System.out.println("c3: " + c3); // 66
// InputDataCheckNaNExample1
String userInput = "12345";
double val = Double.valueOf(userInput);
double currentBalance = 10000.0;
currentBalance += val;
System.out.println(currentBalance); //22345.0
// InputDataCheckNaNExample2
String userInput = "NaN";
double val = Double.valueOf(userInput);
double currentBalance = 10000.0;
if(Double.isNaN(val)) {
System.out.println("Nan이 입력되어 처리할 수 없음");
val = 10.0;
}
currentBalance += val;
System.out.println(currentBalance);
// 20, -20 = 0
//부호화절대값 : 00010100 00010100 00010100
//1의 보수 : 11101011 11101100
//2의 보수 : +1 ----------
// -------- 1(carry는 버립니다.) 00000000 = 0
// 11101100 (-20)
//조건문(Conditioner Statement)
int score = 93;
if(score>=90) {
System.out.println("점수가 90보다 큽니다.");
System.out.println("등급은 A 입니다.");
}
if(score< 90) {
System.out.println("점수가 90보다 작습니다.");
System.out.println("등급은 B 입니다.");
}
//문제] 영어점수를 입력하여 학점을 부여하는 프로그램을 작성하세요. - 단순IF문
Scanner sc = new Scanner(System.in);
System.out.println("영어점수를 입력하세요");
int eng = sc.nextInt();
if(eng<= 100 && eng >=90) {System.out.println("A학점입니다.");
}
if(eng<=89 && eng >=80) {System.out.println("B학점입니다.");
}
if(eng<=79 && eng >=70) {System.out.println("C학점입니다.");
}
if(eng<=69 && eng >=60) {System.out.println("D학점입니다.");
}
if(eng<=59 && eng >=0) {System.out.println("F학점입니다.");
}
//조건연산자 : (조건식) > ? 참 : 거짓;
Scanner sc = new Scanner(System.in);
System.out.println("영어점수를 입력하세요");
int eng = sc.nextInt();
char grade = (eng>=90) ? 'A' : (eng>=80) ? 'B' : (eng >=70) ? 'C' : (eng >=60) ? 'D' : 'F';
System.out.println(grade);
//
//문제] 올해년도를 입력하여 짝수해인지, 홀수해인지 판별하여 출력하세요. - {}괄호 안쓰고도 가능.
Scanner sc = new Scanner(System.in);
System.out.println("올해 년도를 입력하세요");
int year = sc.nextInt();
if(year % 2 == 0)
System.out.println(year + "년은 짝수해입니다.");
else
System.out.println(year + "년은 홀수해입니다.");
//문제] 홍길동의 수학 성적이 85점 입니다.
// 70점 이상이면 합격으로 하고, 아니면 불합격 으로 처리하는 프로그램을 작성하세요.
String name = "홍길동";
int math = 85;
//조건식 : 수학점수가 70점보다 크거나 같으면
if(math >= 70)
System.out.println(name +"님은 " +math + "점으로 합격입니다.");
else // 아니면
System.out.println(name +"님은 " +math + "점으로 불합격입니다.");
//조건연산자 : (조건식) > ? 참 : 거짓; //if문의 간소화
int math = 85;
String pass = (math >= 70) ? "합격" : "불합격";
System.out.println(pass);
//문제] 어떤 숫자를 입력받아서, 음수인지, 양수인지, 0인지를 판별하여 출력하세요.
Scanner sc = new Scanner(System.in);
System.out.println("숫자를 입력하세요");
int nu = sc.nextInt();
if(nu < 0)
System.out.println(nu + "값은 음수입니다.");
else if(nu > 0)
System.out.println(nu + "값은 양수입니다.");
else
System.out.println(nu + "값은 0입니다.");
//조건연산자 : (조건식) > ? 참 : 거짓;
String x = (su > 0) ? "양수":(su<0) ? "음수" : "0";
System.out.println(x);
//난수 발생 클래스 : Random(), Math()
//1~6사이의 난수를 발생하여 출력해 보세요. : 로또, 복권, 게임,
// int num = (int)(Math.random()*6 + 1); // 0을 제거하고 1~6사이 난수발생
int num = (int)(Math.random()*6); // 0~5사이 난수발생
Random rand = new Random(); //Random 클래스 이용해서 객체 생성
int su = rand.nextInt(6) + 1;
System.out.println(su);
if(num == 1)
System.out.println("아이에게 장난감을 사줍니다.");
if(num == 2)
System.out.println("저축을 합니다.");
if(num == 3)
System.out.println("놀이동산에 놀러 갑니다.");
if(num == 4)
System.out.println("용돈으로 5000원을 줍니다.");
if(num == 5)
System.out.println("자전거를 삽니다.");
if(num == 6)
System.out.println("운동화를 삽니다.");
//문제] 은행에 저축을 합니다. 금액은 입력에 따릅니다.
//저축액이 100만원 이면, 하이마트에 가서 노트북을 삽니다.
//저축액이 80만원 이상이면, 멋진 양복을 삽니다.
//저축액이 60만원 이상이면, 아이스크림을 삽니다.
//저축액이 40만원 이상이면, 영화관람을 합니다.
//저축액이 20만원 이상이면, 한턱 쏩니다.
//저축액이 10만원 이상이면, 게임기를 삽니다.
//저축액이 5만원 이상이면, 라면한박스를 삽니다.
//저축액이 3만원 이상이면, 뷔페를 가서 저녁을 먹습니다.
//저축액이 2만원 이하이면, 집에서 열공을 합니다.
//그리고, STOP을 입력하면 프로그램이 중지합니다.
// 누적금액 매번저축금액
int sbanking = 0, banking = 0, money2 = 0;
String stop = " "; // 중지변수
String money = " "; // 입력금액 문자 문자데이터
Scanner sc = new Scanner(System.in);
while(true) {
while(true) {
System.out.println("저축할 금액를 입력하세요");
money = sc.next();
if(money.equals("STOP")) {
System.exit(0);
}
money2 = Integer.parseInt(money);
if(money2 > 0) {
banking = money2;
sbanking+=banking;//누적부분
System.out.println("은행에 저축한 금액은 = " + money2); // 1200
System.out.println("누적 금액은 = " + sbanking); // 1200 + 2300 + ?
}else {
System.out.println("금액을 다시 입력해 주세요.");
continue;
}
if(sbanking > 1000000) {
System.out.println("하이마트로 이동");
System.out.println("노트북 구매");
break;
} else if(sbanking >= 800000) {
System.out.println("양복점으로 이동");
System.out.println("정장 구매");
break;
} else if(sbanking >= 600000) {
System.out.println("베스트샵으로 이동");
System.out.println("디카 구입");
break;
} else if(sbanking >= 400000) {
System.out.println("영화관으로 이동");
System.out.println("영화관람/팝콘 구매");
break;
}else if(sbanking >= 200000) {
System.out.println("포장마차로 이동");
System.out.println("한턱 쏩니다");
break;
}else if(sbanking >= 100000) {
System.out.println("피시방으로 이동");
System.out.println("배틀넷 구매");
break;
}else if(sbanking >= 50000) {
System.out.println("GS25로 이동");
System.out.println("슈퍼콘 구매");
break;
}else if(sbanking >= 30000) {
System.out.println("애슐리로 이동");
System.out.println("식사");
break;
}else
System.out.println("집에서 열공합니다.!!");
break;
}
}
//배수 구하기
//임의의 수를 입력받아서, 그 수가 3, 5, 7, 9의 배수인지를 판별하여 출력합니다.
Scanner sc = new Scanner(System.in);
System.out.println("숫자를 입력하세요");
int x = sc.nextInt();
if(x%3==0)
System.out.println(x + "는 3의배수입니다.");
if(x%5==0)
System.out.println(x + "는 5의배수입니다.");
if(x%7==0)
System.out.println(x + "는 7의배수입니다.");
if(x%9==0)
System.out.println(x + "는 9의배수입니다.");
else
System.out.println("3,5,7,9의 배수가 아닙니다.");
//위의 소스를 줄여서 작성해보세요.
if(x%3==0 || x%5==0 || x%7==0 || x%9==0) {
System.out.println("3,5,7,9의 배수 중 하나입니다.");
} else {
System.out.println("3,5,7,9의 배수가 아닙니다.");
}
//임의의 수를 입력 받아서, 그 수가 기준수보다 큰수인지, 작은수인지, 같은수 인지를 판별하여 출력하세요.
//hint > 555
int hint = 555;
Scanner sc = new Scanner(System.in);
System.out.println("숫자를 입력하세요");
int x = sc.nextInt();
if(x>hint) {System.out.println(x + "가 큰 수 입니다.");
} else if(x<hint) {System.out.println(x + "가 작은 수입니다.");
} else {System.out.println(x + "가 같은 수입니다.");
}
//임의의 수를 입력받아서, 1~100 사이의 숫자인지 판별하고, 그 수가 7의 배수인지 확인하여 출력하세요.
Scanner sc = new Scanner(System.in);
System.out.println("숫자를 입력하세요");
int x = sc.nextInt();
if(x>100 && x<0){
System.out.println(x + "는 1~100사이의 숫자가 아닙니다.");
}else if(100>=x && x>=1 && x%7 == 0) {
System.out.println(x + "는 1~100 사이의 숫자중 7의 배수입니다.");
}else{
System.out.println(x +"는 1~100 사이의 숫자중에서 7의 배수가 아닙니다.");
}
//숫자 두 개를 입력받아서, max, min을 판별하여 출력하세요.
Scanner sc1 = new Scanner(System.in);
System.out.println("숫자를 입력하세요");
int x = sc1.nextInt();
Scanner sc2 = new Scanner(System.in);
System.out.println("숫자를 입력하세요");
int y = sc2.nextInt();
if(x > y) {
System.out.println("최대값은 " + x + " 최소값은" + y + "입니다.");
} else if(x < y){
System.out.println("최대값은 " + y + " 최소값은" + x + "입니다.");
} else {System.out.println("두 수의 값은 같습니다.");
}
//강사님 풀이
int max = 0, min = 0;
Scanner sc = new Scanner(System.in);
System.out.println("숫자를 입력하세요");
int x = sc.nextInt();
int y = sc.nextInt();
if(x > y) {
max = x;
min = y;
} else if(x < y){
max = y;
min = x;
} System.out.println("max = " + max + ", min = " + min);
}
}
'Bitcamp > BITCAMP - Java' 카테고리의 다른 글
4일차 (0) | 2019.06.27 |
---|---|
3일차 - 과제 (0) | 2019.06.26 |
2일차 - 과제 (0) | 2019.06.26 |
2일차 - GUISample1 (0) | 2019.06.25 |
2일차 (0) | 2019.06.25 |
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class 과제0625 {
public static void main(String[] args) throws IOException {
// [과제1]
int aa=100, bb=200, cc=10, dd=20, xx, yy, sumsum, hap;
// aa++;
System.out.println(aa++); // 100(101)
// --cc;
System.out.println(--cc); // 9
xx = (aa++) + cc;
System.out.println(xx); // 101(102) + 9 = 110
// dd++;
System.out.println(dd++); // 20(21)
sumsum = cc + aa++;
System.out.println(sumsum); // 9 + 102(103) = 111
hap = bb++ - aa + cc;
System.out.println(hap); // 200(201) - 103 + 9 = 106
yy = sumsum + hap;
System.out.println(yy); // 111 + 106 = 217
// [과제2] 1과 2의 숫자를 대상으로 관계(비교) 연산자 6가지를 구현하여 결과를 출력하세요.
int a = 1, b = 2;
boolean result7 = a < b;
System.out.println("1 < 2 연산의 결과는 = " + result7);
boolean result8 = a > b;
System.out.println("1 > 2 연산의 결과는 = " + result8);
boolean result9 = a >= b;
System.out.println("1 >= 2 연산의 결과는 = " + result9);
boolean result10 = a <= b;
System.out.println("1 <= 2 연산의 결과는 = " + result10);
boolean result11 = a == b;
System.out.println("1 == 2 연산의 결과는 = " + result11);
boolean result12 = a != b;
System.out.println("1 != 2 연산의 결과는 = " + result12);
// [과제3] BufferedReader 클래스를 이용하여 두 수를 입력받아, 관계 연산 6가지를 프로그램 하세요.
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("첫번째 숫자 입력 : ");
String x = br.readLine();
float x2 = Float.parseFloat(x);
System.out.println("두번째 숫자 입력 : ");
String y = br.readLine();
float y2 = Float.parseFloat(y);
boolean result = x2 < y2;
System.out.println("x < y 연산의 결과는 = " + result);
boolean result2 = x2 > y2;
System.out.println("x > y 연산의 결과는 = " + result2);
boolean result3 = x2 >= y2;
System.out.println("x >= y 연산의 결과는 = " + result3);
boolean result4 = x2 <= y2;
System.out.println("x <= y 연산의 결과는 = " + result4);
boolean result5 = x2 == y2;
System.out.println("x == y 연산의 결과는 = " + result5);
boolean result6 = x2 != y2;
System.out.println("x != y 연산의 결과는 = " + result6);
// * API문서 찾아 생성자, 메소드 정리하기
// - Integer, Float, System, String
// 오라클 사이트에서 APIs로 들어가서 찾아보면 됨.
// Integer
// 1. 생성자 : int value, String s
// 2. 메소드 : bitCount, byteValue, compare, compareTo, decode, divideUnsigned, doubleValue, equals, floatValue, getInteger...
// Float :
// 1. 생성자 : double value, float value, String s
// 2. 메소드 : byteValue, compare, compareTo, doubleValue, equals, floatToIntBits, floatToRawIntBits, floatValue, hashcode, intBitsToFloat, intValue, isFinite, isInfinite, isNan, longValue, max, min, parseFloat, shortValue, sum, toHexString, toString, valueOf
// System :
// 1. 생성자 : 없음
// 2. 메소드 : arraycopy, clearProperty, console, currentTimeMillis, exit, gc, getenv, getProperties, getSecurityManger, inheritedChannel, lineSeparator, load, loadLibrary, mapLibraryName, nanoTime, runFinalization, runFinalizersOnExit, setErr, setIn, setOut, setProperties, setProperty, setSecurity, setSecurityManager
// String :
// 1. 생성자 : String()...
// 2. 메소드 : charAt, codePointAt, codePointBefore, compareTo, concat, contains, contentEquals, copyValueOf, getBytes...
'Bitcamp > BITCAMP - Java' 카테고리의 다른 글
3일차 - 과제 (0) | 2019.06.26 |
---|---|
3일차 (0) | 2019.06.26 |
2일차 - GUISample1 (0) | 2019.06.25 |
2일차 (0) | 2019.06.25 |
1일차 (0) | 2019.06.24 |
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
/* 프레임 => 보더레이아웃
* 화면구성 => 생성자를 이용
* public : 접근 제한자, 공개적인
* class : 클래스. 객체를 생성하여 쓰기 위한 틀.
* GUISample1 : 클래스 이름
* extends : 상속
* JFrame : 상속을 해줍니다.
* implements : 인터페이스(사전에 미리 설계만 해 놓은 상태의 것.)
* ActionListener : 동작 부분.
*
*/
public class GUISample1 extends JFrame implements ActionListener { // JFrame 클래스상속, ActionListener 인터페이스 상속
//필드 영역 : 클래스 변수, 클래스 메소드
private JButton redBtn;
private JButton blueBtn;
private JButton orangeBtn;
private BorderLayout b1;
private JFrame f;
private JTextField tf;
// 화면 구성
public GUISample1() { // 생성자
f = new JFrame("버튼 만들기 예제"); // 객체 생성과 제목 설정
tf = new JTextField(20);
JPanel p = new JPanel(); // 패널. 컴포넌트를 올려서 사용합니다. 눈에는 보이지 않습니다.
redBtn = new JButton("빨강색"); // 버튼 만들기
blueBtn = new JButton("파란색");
orangeBtn = new JButton("주황색");
b1 = new BorderLayout(); // 배치 관리자 설정
setLayout(b1);
JPanel p2 = new JPanel();
p2.add(tf);
f.add("South", p2);
p.add(redBtn); // 패널에 버튼 붙이기
p.add(blueBtn);
p.add(orangeBtn);
f.add("North", p); // "북쪽"에 프레임에 패널 붙이기(부착)
redBtn.addActionListener(this); // 동작
blueBtn.addActionListener(this);
orangeBtn.addActionListener(this);
f.setBounds(300, 300, 600, 500); // x y 좌표와 넓이, 높이 설정
f.setVisible(true); // 화면 보이기. false로 하면 안보임.
}
public static void main(String[] args) {
// GUISample1 gs1 = new GUISample1();
new GUISample1();
}
@Override // 어노테이션 기법
public void actionPerformed(ActionEvent e) { // 동작 구현 부분.
String cmd = e.getActionCommand();
if (cmd.equals("빨강색")) {
redBtn.setBackground(Color.red);
tf.setText(cmd + "이 선택되었습니다.");
} else if (cmd.equals("파란색")) {
blueBtn.setBackground(Color.blue);
tf.setText(cmd + "이 선택되었습니다.");
} else if (cmd.equals("주황색")) {
orangeBtn.setBackground(Color.orange);
tf.setText(cmd + "이 선택되었습니다.");
}
}
}
주요내용 : 명시적 형변환, 강제적 형변환, 지수승, API 문서보는법, GUI구현, 데이터형, 연산자(산술, 관계, 논리, 복합대입, 증감, bit)
// 명시적(강제적) 형변환2
// 1. 묵시적 형변환(문자 + 숫자 = 문자, 정수형 + 실수형 = 실수형, float + double = double)
// (자동형변환)
float f = 3.14159267f;
System.out.println(f); // 3.1415927
int i = 3000;
System.out.println(i); // 3000
float sum = f + i;
System.out.println(sum); // 3003.1416
// 2. 강제적 형변환(원하는 대로 변경) : 상황에 따른 형변환이 필요. 형변환은 출력단계에서 할수도있고, 그전단계에서 할수도 있다.(그때
// 그때 다르다)
System.out.println((int) f);// 3
System.out.println((float) i); // 3000.0
float sum2 = f + i;
System.out.println((int) sum2); // 3003
// 지수승 : 가장 큰 값이나 가장 작은 값을 표현, 오차발생.
double e1 = 333.1415e-3;
double e2 = 15.123456e7;
double e3 = 1234567.123e-7;
System.out.println(e1); // 0.331415
System.out.println(e2); // 151234560.0
System.out.println(e3); // 0.1234567123
// 10진수, 2진수, 8진수, 16진수의 관계
int x = 100; // 10진수
int y = 0100; // 8진수
int z = 0x100; // 16진수
System.out.println(x); // 100
System.out.println(y); // 64
System.out.println(z); // 256
// 근대 컴퓨터의 효시 : 중국 역학(0,1) => 라이프니쯔 => 폰노이만
// 10진수 : 사람이 주로 사용.
// 2진수 : 0, 1 => 0000, 0001, 0011, 0100, 0101...
// 8진수 : 0~7, 10~17, 20~27, 30~37, 40~47, 50~57, 60~67...
// 16진수 : 0~9, A, B, C, D, E, F(15), 10~19, 1A~1F, 20~29, 2A~2F... 이 형태를 주로
// 다룹니다.
// 100은 1100100 이다.(2진수로 표현)
// 100은 144 이다.(8진수로 표현)
// 8진수는 = 2의 3승(3bit) -> 2진수로 표현된 것을 3개씩 묶어서 표현
// 001 100 100 = 144
// 16진수 = 2의 4승(4bit) -> 2진수로 표현된 것을 4개씩 묶어서 표현
// 0110 0100 = 64
// <API 문서보기>
// 오라클 사이트에서 APIs로 들어가서 찾아보면 됨.
// java.lang.*; 생략이 가능하다. 원래는 java.lang.system.gc 이런식으로 작성하는게 맞음.
System.gc(); // 메모리청소
System.out.println(Byte.MIN_VALUE + " ~ " + Byte.MAX_VALUE); // byte의 최소값 ~ 최대값(-128 ~ 127)
System.out.println(Short.MIN_VALUE + " ~ " + Short.MAX_VALUE); // short의 최소값 ~ 최대값(-32768 ~ 32767)
System.out.println(Integer.MIN_VALUE + " ~ " + Integer.MAX_VALUE); // integer의 최소값 ~ 최대값(-2147483648 ~
// 2147483647)
// <GUI구현> -> GUISample1.java
// public class Button extends Component implements Accessible
// This class creates a labeled button.
// The application can cause some action to happen when the button is pushed.
// This image depicts three views of a "Quit" button as it appears under
// the Solaris operating system:
// 데이터형(타입)
// 1. byte(1byte) :2^7 int형으로 변환
byte ba = 10;
byte bb = 20;
byte bc = (byte) (ba + bb); // byte는 기본적으로 int 취급을 하므로, cast를 해야하거나 아랫줄처럼 작성.
int bc2 = ba + bb;
System.out.println("byte = " + bc); // 30
// 2. short(2byte) : 2^15 int형으로 변환
short sa = 10;
short sb = 20;
short sc = (short) (sa + sb);
int sc2 = sa + sb;
System.out.println("short = " + sc2);// 30
// 3. int(4byte) : 2^31
int ia = 10;
int ib = 20;
int ic = ia + ib;
System.out.println("integer = " + ic); // 30
// 4. long(4byte) : L자 붙이기
long la = 30L;
long lb = 50L;
long lc = la + lb;
System.out.println("long = " + lc); // 80
// 5. float(4byte) : f자 붙이기
float fa = 30.67f;
float fb = 45.12f;
float fc = fa + fb;
System.out.println("float = " + fc); // 75.79
// 6. double(8byte) : 2^63
double da = 12.0;
double db = 45.123;
double dc = da + db;
System.out.println("double = " + dc); // 57.123
// 문제] 이름과 나이를 입력받아서(버퍼드 or 스캐너 사용) 출력하는 프로그램을 작성하세요.
// 출력결과> 당신의 이름은 홍길동이고, 나이는 123세 입니다.
Scanner sca = new Scanner(System.in);
System.out.println("이름를 입력하세요.");
String nm = sca.nextLine();
System.out.println("나이를 입력하세요.");
int age = sca.nextInt();
System.out.println("당신의 이름은 " + nm + "이고, 나이는 " + age + "세 입니다.");
// 연산자 : Operator
// 1.산술연산자(+, -, *, /(몫), &(나머지))
int x = 50, y = 30;
int z = x + y;
int z2 = x - y;
int z3 = x * y;
int z4 = x / y;
int z5 = x % y;
System.out.println(z); // 80
System.out.println(z2); // 20
System.out.println(z3); // 1500
System.out.println(z4); // 1
System.out.println(z5); // 20
// 문제1] 국어, 영어, 수학 점수를 입력 받아서, 합계와 평균을 구하세요.
// 4. args[] : 강사님 풀이법. run as configurations -> argument 값에 입력해서 실행하는 방법
int kor, eng, mat, total;
double avr;
kor = Integer.parseInt(args[0]);
eng = Integer.parseInt(args[1]);
mat = Integer.parseInt(args[2]);
total = kor + eng + mat;
avr = total / 3.0;
System.out.println("합계는 " + total + "이고, 평균은 " + avr + "입니다.");
<문제1 내가 풀이한방법 - scanner 버전>
Scanner sca = new Scanner(System.in);
System.out.println("국어점수를 입력하세요.");
int kr = sca.nextInt();
System.out.println("영어점수를 입력하세요.");
int en = sca.nextInt();
System.out.println("수학점수를 입력하세요.");
int math = sca.nextInt();
int sum3 = kr + en + math;
int avg3 = sum3 / 3;
System.out.println("합계는 " + sum3 + "이고, 평균은 " + avg3 + "입니다.");
// 2.관계연산자 : 이항연산, x <= y, x >= y, x == y, x!=y : true/false
int x = 100, y = 200;
boolean result = false;
// and(&&)
result = x < y && y >= x;
System.out.println(result); // t t = t
result = x < y && y < 300;
System.out.println(result); // t t = t
result = x > y && y++ > 300;
System.out.println(result); // f f = f
result = x < y && ++y > 200;
System.out.println(result); // t t = t
result = x == y && y != x;
System.out.println(result); // f t = f
// or(||)
result = x < y || y >= x;
System.out.println(result); // t t = t
result = x < y || y < 300;
System.out.println(result); // t t = t
result = x > y || y++ > 300;
System.out.println(result); // f f = f
result = x < y || ++y > 200;
System.out.println(result); // t t = t
result = x == y || y != x;
System.out.println(result); // f t = t
// 3. 논리연산자
//-----------------------------------------------
// A B and or not exor nand nor
//-----------------------------------------------
// 0 0 0 0 1 -> 0 0 1 1
// 0 1 0 1 0 -> 1 1 1 0
// 1 0 0 1 1 1 0
// 1 1 1 1 0 0 0
//-----------------------------------------------
// 4. 복합대입 연산자
// 산술연산 + 대입 연산 = 복합 대입, 단축연산자
// +=, -=, *=, .=, %=(나머지)
int x = 250;
int y = 380;
int sum3 = x + y;
x += 1000; // x = x + 1000
System.out.println(x);// 1250
x -= 350; // x = x - 350
System.out.println(x);// 900
x *= 5; // x = x * 5
System.out.println(x);// 4500
x /= 3; // x = x / 3
System.out.println(x);// 1500
x %= 2; // x = x % 2
System.out.println(x);// 0
// 5. 증감연산자
// 1증가(++), 1감소(--)
// 유형 : ++x, x++(대입 후 연산), --x(연산 후 대입), x--
int x = 0, y = 10, z = 50, sum1, sum2;
x++;
System.out.println(x);// 1
x--;
System.out.println(x);// 0
++x;
System.out.println(x);// 1
sum1 = x + ++y - z--;
System.out.println(sum1);// 1+11-50(49는 기억) = -38
sum2 = sum1++ - y;
System.out.println(sum2);// -38(-37) - 11 = -49
z--;
System.out.println(z);// 48
// 문제] a=0, b=10, c=20, d=30, e=40, sum1=0, sum2=0;
int a = 0, b = 10, c = 20, d = 30, e = 40, sum1 = 0, sum2 = 0;
b++;
System.out.println(b);// 11
sum1 = c-- + --e - a++; // 대입할 대상이 있으면 기억(기억하는 것은 다음 연산에 참여)
System.out.println(sum1);// 20(19) + 39 - 0(1) = 59
sum2 = sum1 - c + a;
System.out.println(sum2);// 59 - 19 + 1 = 41
sum1 = c++ - a-- + b - --d;
System.out.println(sum1);// 19(20) - 1(0) + 11 - -29 = 0
sum2 = --c + e++;
System.out.println(sum2);// 19 + 39(40) = 58
sum2 = c + e;
System.out.println(sum2);// 19 + 40 = 59
// 6. bit연산자(and, or, not, exor, nand, nor, <<, >>, >>>)
// 통신공학, 전자공학, 전기공학, 반도체공학 등에서 임베디드 시스템으로 사용
int x = 20;
int y = 30;
// 128 64 32 16 8 4 2 1 (8비트로 표현한 것.)
// x 20 => 0 0 0 1 0 1 0 0
// y 30 => 0 0 1 1 1 1 1 0
//------------------------------
// AND연산 0 0 0 1 0 1 0 0 -> 16 + 4 = 20 //참참 일때만 참.
// OR연산 0 0 0 1 1 1 1 0 -> 16 + 8 + 4 + 2 = 30 // 하나만 참 이면 참.
// EXOR연산 0 0 0 0 1 0 1 0 -> 8 + 2 = 10 // 같0 다1.
int z = x & y;
System.out.println("&연산 : " + z);// 20
int z2 = x | y;
System.out.println("|연산 : " + z2); // 30
int z3 = x ^ y;
System.out.println("ExoR연산 : " + z3); // 10
int z4 = x << 3; // x2만큼 늘어납니다.
System.out.println("shift연산 : " + z4); // 160
// 128 64 32 16 8 4 2 1 (8비트로 표현한 것.)
// x 20 => 0 0 0 1 0 1 0 0
//shift연산 0 0 0 1 0 1 0 0 0 -> 32 + 8 = 40
//shift연산 0 0 1 0 1 0 0 0 0 -> 64 + 16 = 80
//shift연산 0 1 0 1 0 0 0 0 0 ->128 + 32 = 160
int z5 = y >> 3; // x2만큼 줄어듭니다.
System.out.println("shift연산 : " + z5); // 3
// 128 64 32 16 8 4 2 1 (8비트로 표현한 것.)
// y 30 => 0 0 0 1 1 1 1 0
//shift연산 0 0 0 0 1 1 1 1 0 -> 15
//shift연산 0 0 0 0 1 1 1 1 0 -> 7
//shift연산 0 0 0 0 1 1 1 1 0 -> 3
'Bitcamp > BITCAMP - Java' 카테고리의 다른 글
3일차 - 과제 (0) | 2019.06.26 |
---|---|
3일차 (0) | 2019.06.26 |
2일차 - 과제 (0) | 2019.06.26 |
2일차 - GUISample1 (0) | 2019.06.25 |
1일차 (0) | 2019.06.24 |
주요내용 : casting, scanner, char, String, subString, 대소문자변환, 형변환, indexOf, equals, Date Class, Calendar Class, Unicode, StringTokenizer
import java.util.Calendar;
import java.util.Date;
import java.util.Scanner;
import java.util.StringTokenizer;
public class hellojava {
@SuppressWarnings("deprecation") // 앞으로 쓰지말라는 경고표시
public static void main(String[] args) {
System.out.println("안녕하세요?"); // 화면에 내용(안녕하세요?)을 출력합니다. 한줄짜리 주석
System.out.println("HelloJava");
System.out.println("반갑습니다.");
/*
* System : 클래스 out : 객체 println : 메소드 ("안녕하세요"?) : 매개변수 값 ; : 문장의 끝
*
*/
// int x = 100; // 정수형 데이터 100을 변수 x에 저장하시오.
// int y = 300;
// int z = x + y; // 덧셈
// System.out.println(z);//400
/*
* int : 정수형 4바이트 메모리 x : 변수 = : 대입 연산자 (오른쪽의 연산의 결과를 왼쪽으로 저장하시오) 100 : 실제적인 데이터
* ; : 문장의 끝
*/
/*
* 1. 데이터 : 자료 => 정수형(소수점이 없는 수=100), 실수형(소수점이 있는 수=123.45), 문자(character = 알파벳 한 문자(대문자/소문자)='a') 문자열(String => 여러개의 문자로 구성="ABCD"), 특수기호(^,%,$,#,@,!,~,&,(,)) 숫자와 문자
* 2. 변수 : x, y, z....
* 3. 자료형 : byte(1), short(2), int(4), long(4), float(4), double(8), boolean(1bit)
* 4. 메모리 : RAM(8GB) = 주소값(address) = 포인터
* 5. algorithm(알고리즘) : 문제해결방법 => 조건문, 반복문, 배열, 객체지향내용...
* 6. 사고력(국어) + 논리력(수학) = 문제해결능력
*/
/*
* 문제 풀이 방법(프로그래밍 5단계)
* 1. 요구사항 파악 : 문제가 목적, 의도 하는 바를 알아내는 것
* 2. 요구사항 분석 : 인재, 비용, 데이터베이스 사양, 서버 사양, 주변상황...
* 3. 요구사항 설계 : 데이터, 변수, 자료형, 형변환, 객체지향접근(클래스, 인터페이스,...)
* 4. 구현 : coding
* 5. 테스트 : 정상적으로 동작하는지 확인!!!
* 6. 배포 및 유지보수 : 60 ~ 70%가 수입원(회사) : SM(System Management)
* 1~5. : SI
*/
//문제1] 1000 + 5000 = 6000이 나오도록 프로그램을 작성하세요.
// 1. 직접 데이터 입력 방법
int a = 1000, b = 5000;
int c = a + b;
System.out.println(c); // 6000
// 2. 키보드로부터 데이터 입력 방법
// Scanner sc = new Scanner(System.in); //sc라는 객체명은 다른걸로 써도 상관없다.
// System.out.println("첫번째 숫자를 입력하세요.");
// int x = sc.nextInt();// 1000
// System.out.println("두번째 숫자를 입력하세요.");
// int y = sc.nextInt();// 5000
//
// int z = x + y;
// System.out.println("두 수의 덧셈의 합은= " + z);// 6000
// 자바는 데이터가 입력될 때, 대부분(기본적으로) 문자로 인식됩니다.(" ") 문자는 연산을 못하므로, nextInt()를 써야함.(정수형으로 값을 받겠다.)
// 3. 키보드로부터 데이터 입력 방법2
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("첫번째 숫자 입력 : ");
String x = br.readLine(); // "3000" 을 문자열로 받는다. readLine : 한라인 전체를 문자열로 받아서 읽어라. 객체명.메소드명 or 클래스명.클래스메소드명 공식
float xx = Float.parseFloat(x); // 3000.0 parse__ : 들어온값에 대해서 __으로 변환하겠다.
System.out.println("두번째 숫자 입력 : ");
String y = br.readLine(); // "6000"
float yy = Float.parseFloat(y); // 6000.0
float zz = xx + yy;
System.out.println(zz); // 9000.0
System.out.println("연산의 결과는 = " + zz);
/* 7.BufferedReader 클래스 : 버퍼에 데이터를 모은다.(4~8kbyte)
* 6.br : object(객체)
* 5.= : 대입연산자
* 4.new : 메모리 할당 연산자
* 3.BufferedReader : 클래스, 객체의 생성, 성능의 향상
* 2.(new InputStreamReader : 1byte씩 입력받아라.
* 1.(System.in)) : 키보드로부터 데이터를 입력합니다.
* ;
*/
// 문제2를 buffered parse 이용하여 나오도록 해보시오.
// first=250, second= 450, third = 550.000f, 합계를 구하여 출력해 봅니다.
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("첫번째 숫자 입력 : ");
// String x = br.readLine(); // 250
// float xx = Integer.parseInt(x); // 250.0
float xx = Integer.parseInt(br.readLine()); // 한줄로도 쓸수 있다.
System.out.println("두번째 숫자 입력 : ");
String y = br.readLine(); // 450
float yy = Integer.parseInt(y); // 450.0
System.out.println("세번째 숫자 입력 : ");
String z = br.readLine(); // 550.000
float zz = Float.parseFloat(z); // 550.000
float xxx = xx + yy + zz;
System.out.println(xxx); // 1250.0
System.out.println("연산의 결과는 = " + xxx);
//문제2] first=250, second=450, third=550.000f, 합계를 구하여 출력해 봅니다.
int first = 250;
int second = 450;
float third = 550.000f;
int sum;
// casting(강제적 형변환)
sum = (int) ((first + second) + third); // 정수형 + 실수형 => 정수형
System.out.println(sum); // println : 출력 후 줄바꿈
// System.out.print(sum); // print : 출력만 함.
System.out.printf("%d\n", sum); // printf : 형식화된 출력, d : 정수형 , \n : 줄바꿈
float sum2; // 묵시적형변환(자동형변환)
sum2 = (first + second) + third; // 정수형 + 실수형 => 실수형
System.out.println(sum2);
System.out.printf("%5.1f\n", sum2); // f : 실수형
//문제3] 키가 172.56cm입니다. 이 때, 키가 몇 피트 몇 인치인지 알아보세요.
// 1 inch = 2.54cm, 1 feet = 30.48cm = 12 inch
double cm, inch, feet, feetsum, inchsum;
cm = 172.56;
inch = 2.54;
feet = inch * 12;
feetsum = cm / feet;
inchsum = (cm % feet) / inch;
System.out.println(feetsum + "몇 피트," + inchsum + "인치입니다.");
System.out.printf("cm는 %3.2f 피트이고, %3.2f 인치입니다.\n", feetsum, inchsum);
//---------------------------------------------------------------------------------
//문자 데이터 : char(문자), String(문자열)
//---------------------------------------------------------------------------------
char name = 'h';
char x = 'y';
char y = 'e';
char z = 's';
String sign = "yes"; // call by reference(참조형)
System.out.println(name + ", " + sign);
System.out.printf("name = %c, sign = %s \n", name, sign);
// 한글 변수 사용 가능.
String 이름1 = "홍길동";
String 이름2 = "임꺽정";
String 이름3;
이름3 = 이름1 + 이름2; // +는 연결 연산자 기능
System.out.println(이름3);// 홍길동임꺽정
// 문자와 숫자와의 연산
String value = "홍길동";
String value2 = value + 300;
System.out.println(value2); // 홍길동300, 문자 + 숫자 => 문자.
// 대문자와 소문자로 변환
// String str = "Java Programming";
// String ss = str.toUpperCase();//대문자로 변환
// System.out.println(ss); //JAVA PROGRAMMING
//
// String sss = ss.toLowerCase(); //소문자로 변환
// System.out.println(sss); //java programming
//문제4] "It is not the time but will that is wanting" 이라는 문자열이 존재합니다.
//내용 중에서 w라는 문자의 위치를 찾아서 출력하고, 문자열의 전체길이가 얼마인지를 확인하세요.
//charAt(); 해당 문자열을 찾아서 읽어온다.
//index : 0123456789....
String msg = "It is not the time but will that is wanting"; // 참조변수
int len = msg.length();
System.out.println(len); // 47(0~46)
for (int idx = 0; idx < len; idx += 1) { // 반복문 , idx += 1(복합대입연산자)
char ch = msg.charAt(idx);
if (ch == 't') {
System.out.println("찾는 인덱스 위치는= " + idx);//1, 8, ...
}
}
// indexOf() : 문자의 위치 찾기
String msg2 = "J a v a Program is Create Many Objects";
// index : 0123456789....
int idx1 = msg2.indexOf('a');//
System.out.println(idx1);// 2
int idx2 = msg2.indexOf('M');//
System.out.println(idx2);// 26
int idx3 = msg2.indexOf('a', 12);// 12번째 이후로 찾아라.(시작지점)
System.out.println(idx3);// 13
int idx4 = msg2.indexOf("is");
System.out.println(idx3);// 16
// subString(부문문자열 출력)
String msg3 = "J a v a Program is Create Many Objects";
// index : 0123456789....
// String str2 = msg3.substring(8,20);//8이후, 20이전(사이에 있는 것 찾기)
// System.out.println(str2); // Program is C
//
// String str3 = msg3.substring(12);
// System.out.println(str3);//ram is Create Many Objects
// String 클래스 : reference type, 무한대 저장 가능.
/* String 클래스
* str4 : 오브젝트(객체)
* = : 대입연산자
* new : 메모리 할당 연산자
* String : 클래스
* ("홍길동") : 매개변수데이터 값
* ; : 문장의 끝
*/
// equals() : 내용이 동일하면, 같은 주소번지를 부여한다.(내용비교. 메모리 절약.)
String str4 = new String("홍길동");
System.out.println(str4);// 홍길동
String str5 = "홍길동";
System.out.println(str5);// 홍길동
String str6 = "김길동";
System.out.println(str6);// 홍길동
String str7 = "홍길동";
System.out.println(str7);// 홍길동
System.out.println(str4.equals(str5));// true
System.out.println(str4.equals(str6));// false
System.out.println(str5.equals(str7));// true
// == : 주소비교.
System.out.println(str5 == str7);// 주소비교? 내용같은가? true (내용이 같으면 주소도 같음)
System.out.println(str5 == str6);// 주소비교? 내용같은가? false (내용이 다르면 주소도 다름)
//문제5] str = "홍길동", str2 = "홍길동", str3 = "홍마차" 이렇게 존재합니다.
String str = "홍길동";
String str2 = "홍길동";
String str3 = "홍마차";
System.out.println(str.equals(str2));// true
System.out.println(str2.equals(str3));// false
str = str3; // str3을 str에 붓는다.(대입한다)
System.out.println(str.equals(str3));// true
System.out.println(str == str3);// true (같은 데이터는 하나의 주소를 갖는다.)
// Date Class(날짜 출력)
// 1. Date Class
Date currentDate = new Date();
// class Object = class
System.out.println("현재 날짜는= " + currentDate + "입니다.");// 아메리칸 스타일 출력.
// 보통 컴퓨터는 1970년 1월 1일이 기본 설정되어 있습니다.
System.out.println("년도: " + currentDate.getYear());// 취소선 나오는 이유 : 앞으로 쓰지 말아라.
System.out.println("월: " + currentDate.getMonth());
System.out.println("일: " + currentDate.getDay());
System.out.println("날짜: " + currentDate.getDate());// 오늘 날짜.
System.out.println(currentDate.toLocaleString());// 현재 시각(now).
// 2. Calendar Class
Calendar cal = Calendar.getInstance();
System.out.println(cal.get(Calendar.YEAR) + "년"); // 2019년
System.out.println(cal.get(Calendar.MONDAY) + 1 + "월");// 6월
System.out.println(cal.get(Calendar.DATE) + "일");//
System.out.println(cal.get(Calendar.HOUR) + "시"); //
System.out.println(cal.get(Calendar.MINUTE) + "분");//
System.out.println(cal.get(Calendar.SECOND) + "초");//
// 3. Unicode : 한국어, 중국어, 일본어...
// http://www.unicode.org/charts
String str8 = "\uAC00"; // 가
String str9 = "\uB098"; // 나
System.out.println(str8 + str9);// 가나
System.out.println(str9); // 나
// 4. StringTokenizer class : 문자열을 구분자(Delimiter)를 이용하여 구분합니다. 마지막 " " 안에 구분자를 넣는다.
StringTokenizer st = new StringTokenizer("개구리, 소년, 왕눈이, 아로미, 투투", ",");
System.out.println("문자열의 갯수는 = " + st.countTokens() + "개");// 5개
while (st.hasMoreTokens()) { // 추출한 단어가 존재하면
String data = st.nextToken(); // 순서대로 읽어오세요.
System.out.println(data);
}
//문제6]
StringTokenizer st2 = new StringTokenizer("개구리=소년; 왕눈이=아로미; 투투=가재", "=;");
System.out.println("문자열의 갯수는 = " + st2.countTokens() + "개");// 6개
while (st2.hasMoreTokens()) { // 추출한 단어가 존재하면
String data2 = st2.nextToken();
System.out.println(data2);
}
}
}
//ctrl + F11 : 실행
'Bitcamp > BITCAMP - Java' 카테고리의 다른 글
3일차 - 과제 (0) | 2019.06.26 |
---|---|
3일차 (0) | 2019.06.26 |
2일차 - 과제 (0) | 2019.06.26 |
2일차 - GUISample1 (0) | 2019.06.25 |
2일차 (0) | 2019.06.25 |