출처: https://bumcrush.tistory.com/182 [맑음때때로 여름]
package Homework;

import java.sql.Statement;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class Jdbc_Homework1 {

	public static void main(String[] args) {

			// 2020.11.18
		
		Connection conn = null;
		
		try {
			
			Class.forName("oracle.jdbc.driver.OracleDriver");
			System.out.println("Oracle Driver Load !!!");

			
			String jdbcUrl = "jdbc:oracle:thin:@localhost:1521:orcl";
			String user = "scott";
			String password = "tiger";
			
			conn = DriverManager.getConnection(jdbcUrl, user, password);
			System.out.println("데이터베이스에 접속했습니다.");
			System.out.println("");
			
			
			// 인스턴스 생성하기
			PreparedStatement pstmt = null;
			
////////////// 1) EMP 테이블에 새로운 사원 정보를 입력하는 프로그램을 작성해보자.
			// emp : empno, ename, job, mgr, hiredate, sal, comm, deptno
			String sqlQ1 = "insert into emp values (seq_emp_empno.nextval,?,?,?,?,?,?,?)";
			pstmt = conn.prepareStatement(sqlQ1);
			pstmt.setString(1,"hyoseon");
			pstmt.setString(2,"gamer");
			pstmt.setInt(3,7839);
			pstmt.setString(4,"20/11/18");
			pstmt.setInt(5,10000);
			pstmt.setInt(6,2000);
			pstmt.setInt(7,30);
			
			int resultCnt = pstmt.executeUpdate();			
			if (resultCnt>0) {
				System.out.println("");
				System.out.println("-------------------- 문제 1번) 정상입력");
				System.out.println("-------------------- 새로운 사원정보 입력 / ename : hyoseon");
				System.out.println("");
				resultCnt=0;
			}else {
				System.out.println("입력이 되지 않았음");
			}
			
			
			// 부서 리스트 출력
//////////////2) EMP 테이블의 모든 데이터를 출력하는 프로그램을 작성해보자.
			
			
			System.out.println("");
			System.out.println("-------------------- 문제 2번) 모든데이터출력");
			System.out.println("");
			String sqlList="select * from emp order by empno";
			pstmt=conn.prepareStatement(sqlList);
			ResultSet rs = pstmt.executeQuery();
			
			while(rs.next()) {
				System.out.print(rs.getInt(1)+"\t");
				System.out.print(rs.getString(2)+"\t");
				System.out.print(rs.getString(3)+"\t");
				System.out.print(rs.getInt(4)+"\t");
				System.out.print(rs.getString(5)+"\t");
				System.out.print(rs.getInt(6)+"\t");
				System.out.print(rs.getInt(7)+"\t");
				System.out.print(rs.getInt(8)+"\t");
				System.out.println("");
				
			}
////////////// 3) EMP 테이블에 서 “SCOTT” 사원의 급여(sal) 정보를 1000으로 바꾸는 프로그램을 작성해보자.
			String sqlQ3 = "update emp set sal=1000 where ename='SCOTT'";
			Statement stmt = conn.createStatement();
			resultCnt = stmt.executeUpdate(sqlQ3);
			if (resultCnt>0) {
				System.out.println("");
				System.out.println("-------------------- 문제 3번) 정상입력");
				System.out.println("-------------------- 스캇 월급 1000으로 수정!");
				System.out.println("");
			}else {
				System.out.println("입력이 되지 않았음");
			}
////////////// 4)EMP 테이블에 서 “SCOTT” 이름으로 검색한 결과를 출력하는 프로그램을 작성해보자.
			System.out.println("");
			System.out.println("-------------------- 문제 4번) Scott 검색 데이터 출력");
			
			String sqlQ4 = "select * from emp where ename='SCOTT'";
			
			rs = stmt.executeQuery(sqlQ4);
			if(!rs.next()) {
				System.out.println("검색결과 X");
			}else {
				do {
					System.out.print(rs.getInt(1)+"\t");
					System.out.print(rs.getString(2)+"\t");
					System.out.print(rs.getString(3)+"\t");
					System.out.print(rs.getInt(4)+"\t");
					System.out.print(rs.getString(5)+"\t");
					System.out.print(rs.getInt(6)+"\t");
					System.out.print(rs.getInt(7)+"\t");
					System.out.print(rs.getInt(8)+"\t");
					System.out.println("");
				}while(rs.next());
				}
			
			
					

//////////////5.모든 사원정보를 출력하되 부서정보를 함께 출력하는 프로그램을 작성해보자.
			System.out.println("");
			System.out.println("-------------------- 문제 5번) 사원정보 + 부서정보 함께 출력");
			System.out.println("");
			String sqlList2="select * from emp, dept where emp.deptno=dept.deptno";
			pstmt=conn.prepareStatement(sqlList2);
			rs = pstmt.executeQuery();
			
			while(rs.next()) {
				System.out.print(rs.getInt(1)+"\t");
				System.out.print(rs.getString(2)+"\t");
				System.out.print(rs.getString(3)+"\t");
				System.out.print(rs.getInt(4)+"\t");
				System.out.print(rs.getString(5)+"\t");
				System.out.print(rs.getInt(6)+"\t");
				System.out.print(rs.getInt(7)+"\t");
				System.out.print(rs.getInt(8)+"\t");
				System.out.print(rs.getInt(9)+"\t");
				System.out.print(rs.getString(10)+"\t");
				System.out.print(rs.getString(11)+"\t");
				System.out.println("");
				
			}
			
			
		} catch (ClassNotFoundException e) {
	         System.out.println("Driver 로드 실패");
	      } catch (SQLException e) {
	         e.printStackTrace();
	      }
		
		
	}

}

package Friend;

import java.util.InputMismatchException;
import java.util.Scanner;

public class FriendInfoMain {

	public static void main(String[] args) {

		FriendInfoHandler handler = FriendInfoHandler.getInstance();
		Scanner sc = new Scanner(System.in);
		while (true) {
			try {
				System.out.println("** 메뉴선택 **");
				System.out.println(Number.INSERT + " : 입력");
				System.out.println(Number.SEARCH + " : 검색");
				System.out.println(Number.DELETE + " : 삭제");
				System.out.println(Number.ALLPRINT + " : 전체 정보 출력 ");
				System.out.println(Number.SIMPLEPRINT + " : 간단 정보 전체 출력 ");
				System.out.println(Number.EXIT + " : 종료 ");
				System.out.println("선택하세요 >>");
				
				int choice = oneSix();
				sc.nextLine();

				switch (choice) {
				case Number.INSERT:
					handler.addFriend();
					break;
				case Number.SEARCH:
					handler.searchInfo();
					break;
				case Number.DELETE:
					handler.deleteInfo();
					break;
				case Number.ALLPRINT:
					handler.showAllData();
					break;
				case Number.SIMPLEPRINT:
					handler.showAllSimpleData();
					break;
				case Number.EXIT:
					System.out.println("프로그램을 종료합니다.");
					return;
				}
			} catch (InputMismatchException | NumberRange e) {
				System.out.println("1에서 6사이의 숫자만 입력하세요");
				continue;
			}
		}
	}
		
		public static int oneSix() throws NumberRange{
			Scanner sc = new Scanner(System.in);
			int choice=sc.nextInt();			
			if(choice>=7 || choice<0) {
				NumberRange e = new NumberRange(choice);
				throw e;
			}
			return choice;
		} 

	

}
package Friend;

public class NumberRange extends Exception{
	
	int choice;
	
	public NumberRange(int choice) {
			}

}

Math.random()을 쓰다가 중복이 안나오게 하고 싶어서 만들어보았는데 왠지 그냥 쉬운 방법이 또 있을듯..

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
package OCt13;
 
public class memo {
 
    public static void main(String[] args) {
 
        int[] num = new int[10];
 
        for (int i = 0; i < num.length; i++) {
            num[i] = (int) (Math.random() * 10+ 1// 랜덤값 넣기
        }
 
        for (int c : num) {
            System.out.print(c + " ");
        }
        System.out.println();
 
        for (int i = 0; i < num.length; i++) {
            for (int j = i; j < num.length; j++) {
                while (true) {
                    if (i != j && num[i] == num[j]) {
                        int c = num[j];
                        num[j] = (int) (Math.random() * 10+ 1;
                        System.out.println(
                                (i + 1+ "번째숫자 " + num[i] + ", " + (j + 1+ "번째 숫자와 같아서 이 숫자를" + num[j] + "로/으로 변경");
                        System.out.println();
                        for (int a : num) {
                            System.out.print(a + " ");
                        }
                        System.out.println();
                        i = 0// i를 초기화해서 또 같은게 없는지 처음부터 끝까지 다찾음
                    } else {
                        break;
                    }
                }
            }
        }
 
        System.out.println();
        System.out.println("모두 다른 랜덤 숫자 !");
 
    }
}
 
cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
package OCt13;
 
public class ArrayBubbleSort {
 
    public static void main(String[] args) {
 
        // 정수 데이터 10개를 저장하는 배열 생성
        int[] number = new int[10];
 
        // 임의의 숫자 0~9까지의 숫자를 각 배열에 넣기
        for (int i = 0; i < number.length; i++) {
            number[i] = (int) (Math.random() * 10);
            System.out.print(number[i] + " ");
        }
 
        System.out.println();
        System.out.print("====================");
        System.out.println();
        
        for (int i = 0; i < number.length; i++) {
            boolean changed = false// 자리바뀜이 발생했는지 체크
 
            // 자리를 바꿈처리
            for (int j = 0; j < number.length - 1 - i; j++) {
                // 왼쪽 인덱스의 값과 오른쪽 인덱스의 값을 비교
                if (number[j] > number[j + 1]) {
                    int temp = number[j];
                    number[j] = number[j + 1];
                    number[j + 1= temp;
                    changed = true;
                }
 
            }
 
            for (int a : number) {
                System.out.print(a + " ");
            }
            System.out.println();
 
            if (!changed) {
                System.out.println("=======================");
                break;
            }
 
        }
 
        for (int a : number) {
            System.out.print(a + " ");
        }
 
    }
 
}
 
cs

- for문을 이용한 역순 출력

1
2
3
4
5
6
7
8
9
10
11
12
13
 
      public static void main(String []args) {
      //변환할 문자열
      String str = "Reverse this strings";
 
      //전체길이에서 0인덱스를 포함해 i--를 이용해 반대로 읽어나갑니다.
      for (int i = str.length() -1; i>=0; i--) {
         System.out.print(str.charAt(i));
      }
   }
}
 
 
cs

 

Stringbuffer를 이용한 역순 출력

reverse()

1
2
3
4
5
6
7
8
9
10
11
   public static void main(String []args) {
      // 버퍼를 만듭니다.
      StringBuffer strBuffer = new StringBuffer(); 
      //변환할 문자열
      String str = "Reverse this strings";
      // 버퍼에 문자열을 넣고
      strBuffer.append(str);
      // 버퍼안에 reverse()를 이용해 거꾸로 출력
      System.out.print(strBuffer.reverse());
   }
}
cs

 

nextInt 이후레 nextLine을 사용하면 노란체크한 것처럼 개행이 된다.

 

이를 방지하기 위해 nextInt 다음줄에

nextLine을 하나 넣어주면 된다.

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
package exam;
 
public class boy {
 
//    다음조건을 만족하는 클래스를 구성하자. 구슬치기와 
//    어린아이가 소유하고 있는 구슬의 개수 정보를 담을 수 있다.
//    놀이를 통한 구슬을 주고받음을 표현하는 메서드가 존재한다.
//    두 번째 조건은 두 아이가 구슬치기를 하는 과정에서 구슬의 잃고 얻음을 의미하는 것이다.
 
int numOfMarble;
String name;
 
// 어린이의 이름과 구슬의 개수를 설정하는 메서드
 
void setBoy(String boyname, int num) {
name = boyname;
numOfMarble = num;
}
 
// 게임의 결과가 실패 -> 구슬 감소
 
void lose(int num) {
numOfMarble -=num;
}
 
// 게임의 결과가 승리 -> 구슬 증가
void win(int num) {
numOfMarble +=num;
}
 
// 게임 후 승리 메서드 : 대상(boy), 구슬의 개수
void playWin(boy boy, int num) {
// 나는 승리 나의 구슬의 개수는 증가
win(num);
// 상대방은 패배 > 감소
boy.lose(num);
}
 
// 보유 구슬 출력
 
void showData() {
System.out.println(name + "의 구슬의 개수는 "+ numOfMarble);
}
 
 
 
public static void main(String[] args) {
 
//        조건을 만족하는 클래스를 정의하였다면, 다음조건을 만족하는 인스턴스를 각각 생성하자. ( 하나의 클래스만 작성하자 )
//        어린이 1의 보유자산  구슬 15개
//        어린이 2의 보유자산  구슬 9개
 
boy boy1=new boy();
boy boy2=new boy();
 
boy1.setBoy("뽀이1"15);
boy2.setBoy("뽀이2"9);
 
//        인스턴스의 생성이 완료되면 다음의 상황을 main 메서드 내에서 시뮬레이션 하자.
//        “1차 게임에서 어린이 1은 어린이 2의 구슬 2개를 획득한다”
 
boy1.playWin(boy2, 2);
//        “2차 게임에서 어린이 2는 어린이 1의 구슬 7개를 획득한다.”
 
boy2.playWin(boy1, 2);
 
//        마지막으로 각각의 어린이의 보유 구슬의 개수를 출력하고 프로그램 종료.
 
boy1.showData();
boy2.showData();
cs

1. 10으로 나눈 나머지를 구하고 다시 10으로 나눠주는 방식을 취한다.

public static void main(String[] args) {

int num = 12345;

int sum = 0;

		while (num > 0) {
			sum += num%10; 
			num = num/10;
		}
System.out.println("sum="+sum);

}

[실행결과]

15

 

2. 응용 / 회문수 구하기

public static void main(String[] args){

int number = 12321;

int tmp = number;

int result =0; // 변수 number를 거꾸로 변환해서 담을 변수

while(tmp !=0) {

				result*=10;
				result+=tmp%10;
				tmp = tmp/10;
}

if(number == result)

System.out.println( number + "는 회문수 입니다.");

else

System.out.println( number + "는 회문수가 아닙니다.");

} // main

}

 

 

 

답은 199가 맞다.

그런데 마지막에 num++;을 하고 while을 빠져나와서 두번째꺼는 200으로 오답

		int num=0;
		int sum=0;
		
		while(sum<100) {
			num++;
			if(num%2!=0) {
				sum+=num;			
			}else {
				sum-=num;
			}
			System.out.println(num + " " + sum);
			}
		System.out.println(num); // num=199
		int num=1;  // 여기도 바꿨었음
		int sum=0;
		
		while(sum<100) {
			
			if(num%2!=0) {
				sum+=num;			
			}else {
				sum-=num;
			}
			System.out.println(num + " " + sum);
			
			num++;	
		
	}
		System.out.println(num); // num=200 틀린답

수점 셋째자리에서 반올림을 하려면 다음의 과정을 거쳐야한다.

1. 값에 100을 곱한다. 

-> 37.77778 * 100 

2. 1의 결과에 0.5를 더한다. 

-> 3777.778 + 0.5 → 3778.278

3. 2의 결과를 int타입으로 변환한다. 

-> (int)3778,278 → 3778 

4. 3의 결과를 100f로 나눈다. (100으로 나누면 소수점 아래의 값을 잃는다.) 

-> 3778 / 100f → 37.78

 

 

 

1.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
    
        Scanner sc = new Scanner(System.in);
        
        String id;
        String small;
        boolean b; 
        
 
        
        while(true) {
            b=false;
            System.out.print("ID 입력 : ");
            id=sc.next();
            small=id.toLowerCase(); // 대소문자 구별을 위해 소문자로 바꿔줌
            
            for(int i=0 ; i<small.length() ; i++) {
                char a = small.charAt(i);
                int asc = (int)a; // 아스키코드로 변경
                
                if ( asc<97 || asc>122 ) {
                    System.out.println("영문/숫자만 입력하세요");
                    b=true;
                    break;
                }
                else if (asc>48 || asc<58) { // 숫자는 
                    b=false;
                    break;
                }  
    }
            
            if(b==false) {
                System.out.println("입력된 ID는 " + id);
                break;
            }
            
    
cs

 

2.

 

 

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
        
        // 영어만 입력받는 거 만들어보기 + 숫자까지 (영문과숫자로이루어진id입력받기)
        // ID
        
        
        Scanner sc = new Scanner(System.in);
        
        String id;
        String small;
        boolean b; 
        
 
        
        while(true) {
            b=false;
            System.out.print("ID 입력 : ");
            id=sc.next();
            small=id.toLowerCase(); // 대소문자 구별을 위해 소문자로 바꿔줌
            
            for(int i=0 ; i<small.length() ; i++) {
                char a = small.charAt(i);
                int asc = (int)a; // 아스키코드로 변경
                
                if ((96<asc && asc<123|| (47<asc && asc<58) ) {
                    b=false;
                    break;
                }
                else  {
                    System.out.println("영문/숫자만 입력하세요");
                    b=true;
                    break;
                }  
    }
            
            if(b==false) {
                System.out.println("입력된 ID는 " + id);
                break;
            }
            
            
        }
cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
 
import java.util.Arrays;
import java.util.Scanner;
 
public class e1 {
 
        public static void main(String[] args) {
             
            String s; // 학생수
            int stu; // 학생수
            boolean b; // 학생수 숫자입력 판별 boolean
            
            
            Scanner sc= new Scanner(System.in);
            
            // 1. 몇명의 성적을 입력할 것인지 묻기
            while(true) {
                b=false;        
            System.out.print("몇명의 성적을 입력하겠습니까?");
                    s=sc.next();
                    for(int i=0 ; i<s.length() ; i++) {
                        char a = s.charAt(i); // 숫자가 아닌 다른 수를 입력했을 경우 찾기
                        int asc = (int)a; // 아스키코드로 변경
                        if(asc<48 || asc>57) {
                            System.out.println("숫자만 입력해주세요.");
                            b=true;
                            break;
                    }
                    
            }
                    if(b==false) { // 숫자를 입력했음
                    //    System.out.println("OK");
                        stu=Integer.parseInt(s); // 제대로 된 숫자임을 확인한 후 String을 int로 바꿔준다
                    //    System.out.println(stu);// 숫자를 제대로 입력했음을 확인하기 위해 삽입해놓음
                         break;
                    }
            }
            // 2. 사람 수에 맞게 배열 확보
            
            int soo[]= new int[stu]; // 입력받은 사람 수만큼의 배열 확보
                System.out.println(soo.length); // 제대로 받았는지 확인해보기
            
            // 3. 각각의 학생의 점수 입력받기
            
                
                String sco; // 점수
                int sco2; // 점수
                boolean c; // 성적수 숫자입력 판별 boolean
                
                    for(int i=0; i<soo.length ; i++) {
                        while(true){
                            c=false;
                        System.out.print((i+1)+"번째 학생의 성적 = ");
                            sco = sc.next(); // String 점수에 넣어준다.
                            for(int j = 0 ; j<sco.length(); j++) {
                                char m = sco.charAt(j);
                                int asc = (int)m; // 아스키코드로 변경
                                if(asc<48 || asc>57) {
                                    System.out.println("숫자만 입력해주세요.");
                                    c=true;
                                    break;                            
                                    }                        
                            }
                            if (c==false) {
                                sco2=Integer.parseInt(sco);
                                soo[i]=sco2;
                                System.out.println("입력된 성적은" + soo[i]);
                                break;
                            }
                    }
                    }
                    
                    for(int i=0; i<soo.length;i++) {
                        
                    }
                    
                    
                    
                    System.out.println(); 
            // 4. 총점
                    int sum = 0;
                    for(int i=0;i<soo.length;i++) {
                        sum +=soo[i];                        
                    }
                    
                    System.out.println("총점 = " + sum);
            // 5. 평균
            
                    System.out.println("평균은 = " + (sum/soo.length));
                    
            // 6. 최고점수 최소점수
                    Arrays.sort(soo);
                    System.out.println("최고점수는 " + soo[soo.length-1]);
                    System.out.println("최저점수는 " + soo[0]);
 
    }
 
}
 
cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
        
        Scanner sc = new Scanner(System.in);
        int a ; // 랜덤으로 정해질 숫자
        int b ; // 유저로부터 입력받을 숫자
        a=(int)(Math.random()*100)+1;
        
        for(int i=0 ; i<10 ; i++){ // 10번의 기회만 줄것
            System.out.print("숫자를 입력하세요 (1~100): ");
            b=sc.nextInt();
                if(b>a) {
                    System.out.println("정답이 입력한 숫자보다 작습니다");}
                else if(b<a) {
                    System.out.println("정답이 입력한 숫자보다 큽니다");}
                else {
                    System.out.println("정답입니다");
                    break;}
                if(i==9) {
                    System.out.println("10번의 기회를 모두 사용하셨습니다.");
                }
            
    
cs

 

- 여러가지 요소 설정

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
Scanner sc = new Scanner(System.in);
        
        /*
            숫자 찾기 게임
            
            random number
            범위: 1 ~ 100 -> number(71)            
                        
            user 입력: 50
            -> 너무 작습니다
            user 입력: 75
            -> 너무 큽니다
            user 입력: 65
            -> 너무 작습니다
            user 입력: 70
            -> 너무 작습니다
 
        */
        
        // 1.변수의 선언
        int r_num, u_num;
        boolean clear;
        String s_num;
        
        clear = false;
        
        // 2.랜덤 수의 산출(1 ~ 100)
        r_num = (int)(Math.random() * 100+ 1;
        System.out.println("r_num:" + r_num);
        
        // ------------------------ loop -> 10회
        boolean b = false;
        int count = 0;
        
        while(count < 10) {
        
            // 3.유저의 입력
            while(true) {    
                b = false;
                System.out.print((count + 1+ "회 숫자입력 = ");
            //    u_num = sc.nextInt();
                s_num = sc.next();        
                // System.out.println( s_num.length() );
                // abc
                for(int i = 0;i < s_num.length(); i++) {
                    char c = s_num.charAt(i);
                //    System.out.println("c = "+ c);
                    
                    /*
                    if(c != '0' && c != '1' && c != '2' &&
                        c != '3' && c != '4' && c != '5' &&
                        c != '6' && c != '7' && c != '8' &&
                        c != '9') {
                        System.out.println("정상적인 숫자를 입력해 주십시오");
                        b = true;
                        break;
                    }
                    */
                    
                    int asc = (int)c;
                    if(asc < 48 || asc > 57) { // 숫자의 범위
                        System.out.println("정상적인 숫자를 입력해 주십시오");
                        b = true;
                        break;
                    }                    
                }            
                if(b == false) {    // 문제 없음
                    //System.out.println("문제없이 입력함");
                    break;
                }    
                
                System.out.println("b = " + b);
            }
            
            // 문자열 -> 숫자
            u_num = Integer.parseInt( s_num );
                    
            // 4.판정(크다/작다)
            if(u_num > r_num) {
                System.out.println("너무 큽니다");
            }
            else if(u_num < r_num) {
                System.out.println("너무 작습니다");
            }
            else {    // 숫자를 맞춘경우
                clear = true;
                break;
            }
            
            count++;
        }
        // ------------------------
        
        // 5.결과
        if(clear) {
            System.out.println("Game Clear!");            
        }
        else {
            System.out.println("Game Over~");
        }
cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
 
        
    //이중for문 탈출예제
        
        for(int i=0; i<10; i++) {
            
            System.out.println("i = "+i);
        
            for(int j =0; j<5 ; j++){
                System.out.println("\tj = " + j);
                if(i==5 && j==3) {
                    break;  
                    //for문 1개에 break 1개 i=5 j=3에 탈출하지만 다시 i=6부터 돌아간다.
                }
            }
        }
            
    // 이중for문 탈출 방법 1
            
            boolean b = false;
            
            for(int i=0; i<10; i++) {
                
                System.out.println("i = "+i);
            
                for(int j =0; j<5 ; j++){
                    System.out.println("\tj = " + j);
                    if(i==5 && j==3) {
                        b = true;
                    }
                    if(b == true) {
                        break;
                    }
                    
                }
                if(b == true) {
                    break;
    }
 
    }
            
            
        //  이중for문 탈출 방법 2
            
            outside:for(int i=0; i<10; i++) {   // outside를 앞에도 적어줌 ~:
                
                System.out.println("i = "+i);
            
                for(int j =0; j<5 ; j++){
                    System.out.println("\tj = " + j);
                    if(i==3 && j==2) {
                        break outside; // 단어는 outside가 아니라 아무거나 가능  
                        
                    }
                }
            }
            
            
cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
    // 10명의 데이터를 입력받도록 한다.
    
    Scanner sc = new Scanner(System.in);
    
    
    // for문으로 풀기
    int arrNum[] = new int[10];
    
    for (int i =0; i<10 ; i++) {
        System.out.println((i+1)+"번째 데이터 = ");
        arrNum[i] = sc.nextInt();
    }
    
    
    // while문으로 풀기
    int numArr[] = new int[10];
    int w1;
    w1=0;
    
    while (w1<10) {
        System.out.println((w1+1+"번째 데이터= ");
        numArr[w1]=sc.nextInt();
        
        w1++;
    }
            
cs

1
2
3
4
5
6
7
8
9
10
11
12
13
            int n=0;
            
            for(int j=00 ; j<9 ; j++) {
                
                if(j<5
                    n++;
                else n--;
                
                for (int i =0; i<n; i++) {
                    System.out.print("*");
                }
                System.out.println();
            }
cs

참고 링크  : pridiot.tistory.com/24

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
        char arr[] = {'D''W''O''A''B'};
        // 모두 소문자로 변경한 후 출력하라.
        // A=65, a=97 -> 32 
        // System.out.println("ASCII = " + (int)arr[0]);  알파벳을 ASCII 코드로변경해서 출력해보기
        
        int asc = (int)arr[0];    // D의 ASCII코드값 얻기
        asc = asc+32;            // 소문자로 변환        
        char ch = (char)asc;    // 문자로변환
        System.out.println(ch); // 출력
        
        for(int i=0 ; i<arr.length ; i++) {
            char c = arr[i]; // char c에 순서대로 알파벳 넣기
            int asc2 = (int)c; // arr[i]값의 ASCII 코드값 얻기
            asc2 = asc2+32// 소문자로 변환하기
            arr[i] = (char) asc2; // 다시 arr[i]에 소문자로 바뀐 값 넣어주기
            System.out.print(arr[i]);
            
        }
cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
char arrch[] = {'D''W''O''A','B'}; 
// A를 찾아서 a로 변경하고 출력하라 
 
 
//for문으로 
        for (int i=0 ; i < arrch.length ; i++) { 
            if(arrch[i]=='A') { 
                arrch[i]='a'
                System.out.print(arrch[i]);}
            else { 
                System.out.print(arrch[i]);} // DWOaB로 출력
    } 
 
 
System.out.println(""); 
 
//foreach문으로
        
        char arrch1[] = {'D''W''O''A','B'};
        
        
        int index=0 ; // 따로 변수를 줌
        
        for(char c : arrch1) {
            if(c == 'A') {
                arrch1[index] = 'a';
            }
            index++;
        }
        
        for(int i=0; i<arrch1.length;i++) {
            System.out.print(arrch1[i]);
        }
        
 
 
cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
        // 1~100 사이에 있는 숫자 중 짝수들의 합, 홀수들의 합을 구하라.
        
        int sum1=0//짝수합
        int sum2=0//홀수합
        
         for(int i=1 ; 101>i; i++) {
             if(i%2==0) {
                 sum1=sum1+i;
             }
             else {
                 sum2=sum2+i;
             }             
         }
         
         System.out.println("짝수합 = " + sum1);
         System.out.println("홀수합 = " + sum2);
cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
        Scanner sc = new Scanner(System.in);
        
        int a;
        
        System.out.print("숫자를 입력하세요 : ");
        a=sc.nextInt();
        
    
        
        if (a%2==0) {
            System.out.println("짝수입니다");
            }
        else {
            System.out.println("홀수입니다");
        }
cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
         int a; // =3240; // 지불해야할 금액
         int b; //=10000; // 본인이 낸 금액
         
         Scanner money=new Scanner(System.in);
         System.out.print("지불해야할 금액 : ");
         a=money.nextInt();
         System.out.print("낸 금액 : ");
         b=money.nextInt();
         
         
         int c; // 거스름돈
         c=b-a; 
    
         int d,e,f,g,h,i; // 5000원 1000원 500원 100원 50원 10원의 갯수
         
         
         
        /* d=c/5000; // 5000원권의 갯수
         e=(c-(d*5000))/1000; // 1000원권의 갯수
         f=(c-(d*5000)-(e*1000))/500 ;// 500원 갯수
         g=(c-(d*5000)-(e*1000)-(f*500))/100 ; // 100원 갯수
         h=(c-(d*5000)-(e*1000)-(f*500)-(g*100))/50; // 50원 갯수
         i=(c-(d*5000)-(e*1000)-(f*500)-(g*100)-(h*50))/10; // 10원 갯수 */
         
         d=c/5000;
         e=(c%5000)/1000;
         f=(c%1000)/500;
         g=(c%500)/100;
         h=(c%100)/50;
         i=(c%50)/10;
         
         
         System.out.println("5000원 갯수 = " + d);
         System.out.println("1000원 갯수 = " + e);
         System.out.println("500원 갯수 = " + f);
         System.out.println("100원 갯수 = " + g);
         System.out.println("50원 갯수 = " + h);
         System.out.println("10원 갯수 = " + i); 
    
         
cs

+ Recent posts