자바/스프링 개발 부트캠프 3일차( 형변환과 반복문)

어제 푼 문제 간단하게 리뷰
그나마 난이도가 좀 있었던것만 리뷰하겠음..
모든문제는
github에 올려두긴했음
https://github.com/donggonyoo/javaStudyGudee/tree/main/chap3/src/chap3/hard_test
javaStudyGudee/chap3/src/chap3/hard_test at main · donggonyoo/javaStudyGudee
Contribute to donggonyoo/javaStudyGudee development by creating an account on GitHub.
github.com
package chap3.hard_test;
import java.util.Scanner;
/*
* 화면에서 금액입력받아서 500,100,50,10,1원 동전으로 바꾸기.
* 필요한 동전의 갯수 출력하기. 전체동전은 최소 갯수로 바꾼다.
* [결과]
* 금액을 입력하세요
* 5641
* 500원 : 11개
* 100원 : 1개
* 50원 : 0개
* 10원 : 4개
* 1원 : 1개
*/
public class Test1 {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("금액 입력 : ");
int a = scan.nextInt();
int b= a/500;
int c = (a%500)/100;
int d = (a%100) / 50;
int e = a%100 / 10;
int f = a%10;
System.out.println("500원 : "+b);
System.out.println("100원 : "+c);
System.out.println("50원 : "+d);
System.out.println("10원 : "+e);
System.out.println("1원 : "+f);
//방법2
System.out.println("500원 ㅣ "+a/500);
a%=500;
System.out.println("100원 ㅣ "+a/100);
a%=100;
System.out.println("50원 ㅣ "+a/50);
a%=50;
System.out.println("10원 ㅣ "+a/10);
a%=10;
System.out.println("1원 ㅣ "+a);
}
}
\
금액 입력 :
5492
500원 : 10
100원 : 4
50원 : 1
10원 : 4
1원 : 2
@@ 방법 2 @@
500원 ㅣ 10
100원 ㅣ 4
50원 ㅣ 1
10원 ㅣ 4
1원 ㅣ 2
package chap3.hard_test;
import java.util.Scanner;
/*
키보드로 입력 받은 값들을 변수에 기록하고 저장된 변수 값을 화면에 출력하여 확인하세요.
이 때 성별이 ‘M’이면 남학생, ‘M’이 아니면 여학생으로 출력 처리 하세요.
정수 : nextInt()
실수 : nextDouble()
String : next()
[결과]
이름 : 김명신
학년(숫자만) : 3
반(숫자만) : 15
번호(숫자만) : 1
성별(M/F) : F
성적(소수점 아래 둘째 자리까지) : 95.75
3학년 15반 1번 김명신 여학생의 성적은 95.75이다.
*/
public class Test9 {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.print("이름 : ");
String name = scan.next();
System.out.print("학년 : ");
int grade = scan.nextInt();
System.out.print("반 : ");
int ban = scan.nextInt();
System.out.print("번호 : ");
int num = scan.nextInt();
System.out.print("성별(M/W) : ");
String sex = scan.next();
System.out.print("성적 : (소수점 둘쨰자리만)");
double grade_ = scan.nextDouble();
System.out.println(grade+"학년"+ban+"반"+num+"번 "+name+""
+(sex.equalsIgnoreCase("M")?"남학생":"여학생")+"의 성적은 "+grade_);
}
}
이름 : donggonJava
학년 : 2
반 : 5
번호 : 7
성별(M/W) : m
성적 : (소수점 둘쨰자리만)90.42
2학년5반7번 donggonJava남학생의 성적은 90.42
********************* ********************* ********************* ********************* *********************
여기서 기존에 하던것과 다른방식이 하나존재함
문자열을 입력받을 때 scan.nextLine()을 사용했었는데
이제는 scan.next()를 사용함
**nextLine()의 문제점 : int형을 입력받은 후 nextLine()을 호출하면 \n이 지워지지않은 상태로
넘어오기때문에 빈값으로 자동입력이 돼 버림.
그러므로 nextInt() 후에는 nextLine을 한번 적어준 후에 nextLine()으로 입력받았어야 함.
ex)
int num = scan.nextInt();
scan.nextLine();
System.out.print("성별(M/W) : ");
String sex = scan.nextLine();
scan.next() 사용시 이런 번거로운 문제가 없어지는듯 하다.
@@ 조건문에 대해 시작 @@
package chap4;
import java.util.Scanner;
/*
* if-else 조건문
* if(조건식){
* 조건식이 참인 경우 실행}
* else{조건식이 거짓인 경우 실행되는 문장}
*/
public class If_Ex02 {
public static void main(String[] args) {
System.out.print("정수입력 : ");
Scanner scan = new Scanner(System.in);
int score = scan.nextInt();
if(score>=60) {
System.out.println("합격");
}
else {
System.out.println("불합격");
}
}
}
package chap4;
import java.util.Scanner;
/*
* if / else if / else
* if(조건식1){조건식1이 참인경우 실행되는 문장들}
* else if(조건식2){조건식1이거짓이고 조건식2가 참}
* else if(조건식3){조건식1,2 거짓이고 조건식3가 참}
* else{모든조건식이 거짓일 때 실행}
*/
public class If_Ex01 {
public static void main(String[] args) {
System.out.print("점수를 입력 : ");
Scanner scan = new Scanner(System.in);
int score = scan.nextInt();
if(score >=60) {
System.out.println("합격");
}
else {
System.out.println("불합격");
}
if(score>=90) {
System.out.println("A");
}
else if(score>=80) {
System.out.println("B");
}
else if(score >= 70) {
System.out.println("C");
}
else if(score >= 60) {
System.out.println("D");
}
else {
System.out.println("F");
}
}
}
//
점수를 입력 : 56
불합격
F
점수를 입력 : 60
합격
D
점수를 입력 : 70
합격
C
여기서 중요한 함수
String next = scan.next();
char ch = next.charAt(0); //입력된문자의 첫번째 문자
package chap4.exan;
import java.util.Scanner;
/*
* 화면에서 한개의 문자를 입력받아 대소문자 소문자 숫자 기타문자인지출력
* [결과]
* 한개의 문자입력 : A
* 대문자
* 대문자의조건 65~96 (아스키코드) or 'A'<= ch <= 'Z'
* 소문자의조건 97~122 (아스키코드) or 'a'<= ch <= z
* 숫자조건 :48~57(아스키코드) or '0' <= ch <= 9
* 그외
*
*/
public class Exam02 {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
for (int i = 0; i < 5; i++) {
System.out.println("================");
System.out.print("한개의 문자 입력 : ");
String next = scan.next();
char ch = next.charAt(0);//입력된문자의 첫번째 문자
int ascii = ch; //char은 int보다 작음 (자동형변환가능)
System.out.println("AsciiCode :"+ascii);
if(65<=ascii && ascii<=96) {
System.out.println("대문자");
System.out.println("소문자 : "+(char)(ch+32));
}
else if('a'<=ch && ch<='z' ) {
System.out.println("소문자");
System.out.println("대문자 : "+(char)(ch-32));
}
else if('0'<= ch && ch<='9') {
System.out.println("숫자");
}
else {
System.out.println("기타문자");
}
}
}
}
================
한개의 문자 입력 : A
AsciiCode :65
대문자
소문자 : a
================
한개의 문자 입력 : c
AsciiCode :99
소문자
대문자 : C
================
한개의 문자 입력 : :
AsciiCode :58
기타문자
================
한개의 문자 입력 : J
AsciiCode :74
대문자
소문자 : j
================
한개의 문자 입력 : h
AsciiCode :104
소문자
대문자 : H
Switch문
package chap4;
import java.util.Scanner;
/*
* switch ( 조건값 ) {
case 값1 :문장1 break;
case 값2: 문장2 break;
default : 문장 break;
}
*/
public class Switch_01 {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
for (int i = 0; i <5; i++) {
System.out.print("점수입력 : ");
int score = scan.nextInt();
if(score==100) {--score;}
switch (score/10) {
case 10:
case 9:
System.out.println("A학점");
break;
case 8:
System.out.println("B");
break;
case 7:
System.out.println("C");
break;
case 6:
System.out.println("D");
break;
default:
System.out.println("F");
}
switch (score/10) {
case 10:
case 9:
case 8:
case 7:
case 6:System.out.println("PASS");
break;
default:System.out.println("FAIL");
break;
}
System.out.println("============");
}
}
}
점수입력 : 70
C
PASS
============
점수입력 : 60
D
PASS
============
점수입력 : 90
A학점
PASS
============
점수입력 : 100
A학점
PASS
============
점수입력 : 70
C
PASS
============
조금 다른 버전도 존재
(이 방법은 break문을 사용하지 않음 )
package chap4;
import java.util.Scanner;
/*
* switch ( 조건값 ) {
case 값1 :문장1 break;
case 값2: 문장2 break;
default : 문장 break;
}
/ case값 : 대신에
/ case값 -> 을 쓰면 break;사용하지않아도 됨(한줄이상은 {}필요)
*/
public class Switch_01_Ramda {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
for (int i = 0; i <5; i++) {
System.out.print("점수입력 : ");
int score = scan.nextInt();
if(score==100) {--score;}
switch (score/10) {
case 9-> {
System.out.println("A학점");
System.out.println("우수");}
case 8-> {
System.out.println("B");}
case 7->{
System.out.println("C");
System.out.println("분발");}
case 6->{
System.out.println("D");
System.out.println("재수강(선택)");}
default->{
System.out.println("F");
System.out.println("재수강(필수)");}
}
System.out.println("============");
}
}
}
Math.random()과
Random함수
package chap4;
import java.util.Random;
public class Switch02 {
public static void main(String[] args) {
int ranNum = new Random().nextInt(10)+1;
//1~10 임의의 수를 가져옴
int num = (int)(Math.random() * 10)+1;
/*
* 0.0 <= Math.random() <1.0
* 0.0 <= Math.random()*10 <10.0
* 0= <= (int)(Math.random()*10) < 9
* 1 <= (int)(Math.random()*10)+1 < 10
*
*/
switch(ranNum) {
case 1->System.out.println("자전거당첨");
case 2->System.out.println("USB 당첨");
case 3->System.out.println("마우스 당첨");
case 4->System.out.println("냉장고 당첨");
default ->System.out.println("꽝");
}
}
}
내 개인적인 생각은 Random함수가 조금 더 편리하다!!!
난수와 switch문을 사용한 예제풀이
package chap4.exan;
import java.util.Random;
import java.util.Scanner;
/*
* 1,2,3 중 한개의임의의값을 생성해
* 1.가위
* 2.바위
* 3.보자기
* 출력
*
* 시스템 사용자
* 1 1 비김
* 1 2 사용자 이김
* 1 3 시스템 승
*/
public class Exam03 {
public static void main(String[] args) {
String a,b;
for (int i = 0; i < 5; i++) {
int sNum = new Random().nextInt(3) + 1 ;
switch (sNum) {
case 1->a="가위";
case 2->a="바위";
default->a="보자기";}
Scanner scan = new Scanner(System.in);
System.out.print("가위(1),바위(2),보(3) 입력 : ");
int my = scan.nextInt();
switch (my) {
case 1->b="가위";
case 2->b="바위";
default->b="보자기";}
System.out.println("시스템\t사용자");
System.out.println(a+"\t"+b);
if(sNum==1 && my==2 || sNum==2 && my==3
||sNum==3 && my==1) {
System.out.println("나 승리");
}
else if(sNum==my){
System.out.println("동점");
}
else {
System.out.println("시스템 승리");
}
System.out.println("=======");
}
}
}
가위(1),바위(2),보(3) 입력 : 1
시스템 사용자
바위 가위
시스템 승리
=======
가위(1),바위(2),보(3) 입력 : 2
시스템 사용자
바위 바위
동점
=======
가위(1),바위(2),보(3) 입력 : 3
시스템 사용자
보자기 보자기
동점
=======
가위(1),바위(2),보(3) 입력 : 1
시스템 사용자
바위 가위
시스템 승리
=======
가위(1),바위(2),보(3) 입력 : 1
시스템 사용자
보자기 가위
나 승리
=======
Switch문에 쓸 수있는 자료형
byte char short int String
package chap4;
/*
* switch(조건값)
* 조건값으로 사용가능한 자료형
* byte , short, int ,char , String
*/
public class Switch03 {
public static void main(String[] args) {
String str = "1";
switch(str) {
case "1" -> System.out.println(str);
default -> System.out.println("defalut");
}
char ch = 'A';
switch(ch) {
case 'A'-> System.out.println(ch);
default-> System.out.println("defalut");
}
short s = 6; //int , byte 가능
switch(s) {
case 6 : System.out.println(s);break;
default : System.out.println("defalut");break;
}
//중첩switch문 가능
int a = 1,b=2;
switch (a) {
case 1:
switch (b) {
case 2:System.out.println("a : "+a+"b : "+b);
break;}
break; //break를 클릭해보면
//어느 switch문의 break인지 나타남
default:System.out.println("default구문");
}
}
}
반복문
*for문(초기값 : 조건문 : 증감식){
* 조건문이 참인동안 실행되는 문장들
* }
*조건문의결과가 거짓이면 종료
*
*=========while문=================
*while(조건문){
* 조건문의결과가 참인동안 실행
* }
*조건문의 결과가 거짓이면 반복문종료
*처음부터 조건문의결과가거짓이면 문장실행 X
*
*=========do-while문===============
*do{
* 조건문의결과가 참인동안 실행( 무조건 한번 실행됨 )
* } while(조건);
* *조건문의 결과가 거짓이면 반복문종료
* 조건문과상관없이 한번은 실행
package chap4;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
public class LoopEx01 {
public static void main(String[] args) {
System.out.println("반복문없이 1~5 출력하기");
System.out.print(1);
System.out.print(2);
System.out.print(3);
System.out.print(4);
System.out.println(5);
for (int i = 1; i <= 5; i++) {//i :지역변수
System.out.print(i);
if(i==5) {
System.out.println("");
}
}
/*
* 1)int i = 1;
* 2) i<=5 : T <----------| 거짓인경우 반복문 종료
* 3) System.out.print(i); |
* 4) i++; //6 -------|
*/
int count=0; //전역변수 count
while(true) {
count++;
System.out.print(count);
if(count==5) { //count==5일때 \n 후 반복문탈출
System.out.println();
break;}
}
ArrayList<Integer> arrayList = new ArrayList<Integer>(List.of(1,2,3,4,5));
for (Integer integer : arrayList) {
System.out.print(integer);
}
}
}
예제문제(반복문과 char>int 관련)
package chap4.exam;
import java.util.Iterator;
import java.util.Scanner;
/*
* 화면에서자연수입력받아 각 자릿수의 합구하기
* [결과]
* 자연수입력 : 123
* 자리수합 : 6
*/
public class Exam05 {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int sum1=0;
int a = 0;
System.out.print("자연수입력 : ");
int nextInt = scan.nextInt();
int x =nextInt;
while(x>0) {
sum1+=x%10;
x /=10;
}
System.out.println("sum1 : "+sum1);
//////다른방법 ( 심화) !~~~~~~~~~~~~~~~~~~~~~~~
int sum2=0;
System.out.print("자연수 입력 : ");
String next = scan.next();
for (int i = 0; i < next.length(); i++) {
String substring = next.substring(i,i+1);
int int1 = Integer.parseInt(substring);
sum2+=int1;
}
System.out.println("각자릿수합 : "+sum2);
}
}
package chap4.exam;
import java.util.Scanner;
/*
* 화면에서 문자열 입력받아 각 자릿수의 합구하기
* [결과]
* 자연수입력 : 123
* 자리수합 : 6
*/
public class Exam06 {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int sum1=0;
int a = 0;
System.out.print("자연수입력 : ");
String num = scan.next();
for(int i=0 ; i< num.length();i++) {
System.out.print("asci("+num.charAt(i)+"): "
+(int)num.charAt(i)+" - ");
sum1+=num.charAt(i) - '0';
System.out.println((int)('0')+": {0(Ascii}"
+"="+(num.charAt(i) - '0'));
//0을 왜뺄까? :
//아스키코드기준 : 0 ~9 == (48~57)( 아스키코드때문에 0을 뺴주는거임)
}
System.out.println(sum1);
}
}
/////////////////////////////////////////
자연수입력 : 67
asci(6): 54 - 48: {0(Ascii}=6
asci(7): 55 - 48: {0(Ascii}=7
13
중첩반복문을 활용한 예제
package chap4.exam;
import java.util.Scanner;
/*
* 삼각형의 높이를 입력받아 *로 삼각형출력
*/
public class Exam07 {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("삼각형의 높이 출력");
int nextInt = scan.nextInt();
for (int i = 1; i <= nextInt; i++) {
System.out.println();
for (int j = 0; j < i; j++) {
System.out.print("*");
}
}
}
}
삼각형의 높이 출력
6
*
**
***
****
*****
******
public void reverse(int b) {
System.out.println("거꾸로출력");
for (int i = b; i >= 1; i--) {
for (int j = 1; j <=i; j++) {
System.out.print("*");
}
System.out.println();
}
}
public void emptyPrint(int c) {
for (int i = c; i > 0; i--) {
for (int j = 1; j <= c; j++) {
if(i > j) {
System.out.print(" ");
}
else {
System.out.print("*");
}
}System.out.println();
}
}
공백포함 출력
*
**
***
****
/*
* 4: i j
* =======================
* *** 1 123
* ** 2 23
* * 3 3
*/
public void emptyReverse(int d) {
System.out.println("공백포함 거꾸로");
for (int i = 1; i <= d; i++) {
for (int j = 1; j <= d ; j++) {
if(i<=j) {
System.out.print("*");
}
else {
System.out.print(" ");
}
}System.out.println();
//i = 1 j = 1 2 3
// i = 2 j = 123
//i=3 j= 123
}
}
공백포함 거꾸로
***
**
*
심화예제문제 (나의풀이)
여기에 넣어놨음
https://github.com/donggonyoo/javaStudyGudee/tree/main/chap4/src/chap4/hardEx
javaStudyGudee/chap4/src/chap4/hardEx at main · donggonyoo/javaStudyGudee
Contribute to donggonyoo/javaStudyGudee development by creating an account on GitHub.
github.com
귀찮으면 여기서보기
Ex03 : ( 피라미드 별 찍기 )
난이도 : 중상 ( 2for문+for문)
난 구글링으로 찾아서 풀긴했는데
다시 한번 비슷한 알고리즘 문제를 풀어보자
가장 헤맸던 문제 2개만리뷰해볼게요
Exam02
* 화면에서 한개의 문자를 입력받아 대소문자 소문자 숫자 기타문자인지출력
* [결과]
* 한개의 문자입력 : A
* 대문자
* 대문자의조건 65~96 (아스키코드) or 'A'<= ch <= 'Z'
* 소문자의조건 97~122 (아스키코드) or 'a'<= ch <= z
* 숫자조건 :48~57(아스키코드) or '0' <= ch <= 9
* 그외
여기서포인트 : String next ==> next.charAt(0); 으로 첫번째 문자열(char)을 추출
char 형은 int형보다 크기가 작기때문에 형변환가능int ascii = ch; 로 문자열의 아스키코드를 추출해낸다.
그 후
대 ->소 :
조건문을 사용해 아스키코드 65 <= ascii <= 96 으로 대문자만을 받는다`
대문자+32 = 소문자 임을 이용해 (char)(ch+32) 로 아스키코드를 더한 후 char로 다운캐스팅
소->대
또한 'a' <= ch <= 'z' 와 같이 문자열로도 범위설정이 가능함
위에서 얘기했듯이 (char)(ch-32) 로 대문자로만듬
숫자:
숫자는 int a = (int)(ch - '0') 으로 문자열에저장된숫자를 int형으로 바꿔줌
0을 왜빼냐면
0의 ASCII :48 // 1 의 ASCII : 49 // 2 의 ASCII : 50 '..........
로 이루어져있다.
만약에 ch가 '3' 이라 가정해보자
(int)ch 를 해버리게되면 int값에 51 이 들어가게되는거다
(int)(ch - '0') 로 '0'의 ASCII값인 48을 빼줘야 3이라는 int값으로 반환됨
--- 3 = (int)(51 - 48)
그리고 조심해야할 점 이 한가지 더 있음
System.out.println(a+"+20 : "+(a+20)); 여기서 (a+20) 의 괄호를 제거하게되면
문자로인식해 a20과 같은 출력이나오게 됨
package chap4.exam;
import java.util.Scanner;
public class Exam02 {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
for (int i = 0; i < 5; i++) {
System.out.println("================");
System.out.print("한개의 문자 입력 : ");
String next = scan.next();
char ch = next.charAt(0);//입력된문자의 첫번째 문자
int ascii = ch; //char은 int보다 작음 (자동형변환가능)
System.out.println("AsciiCode :"+ascii);
if(65<=ascii && ascii<=96) {
System.out.println("대문자");
System.out.println("소문자 : "+(char)(ch+32));
}
else if('a'<=ch && ch<='z' ) {
System.out.println("소문자");
System.out.println("대문자 : "+(char)(ch-32));
}
else if('0'<= ch && ch<='9') {
System.out.println("숫자");
int a = (int)(ch - '0');
System.out.println(a+"+20 : "+(a+20));
}
else {
System.out.println("기타문자");
}
}
}
}
////////////////////////////////////
한개의 문자 입력 : A
소문자 : a
한개의 문자 입력 : a
대문자 : A
한개의 문자 입력 : 8
'8'의 ascii : 56
'0'의 ASCII : 48
출력(+20) :28
한개의 문자 입력 : ;
기본문자
Exam03
삼각형의 높이가 3 이라고 가정한 알고리즘
-은 공백으로 생각하자 실행이 잘된다면 - 을 없애면 된다!!
(밑에 거꾸로 피라미드 출력하기가 있는데 이 법칙을 꼭 적고 응용하면 됨(k 의숫자가 내려가는방식)
package chap4.hardEx;
import java.util.Scanner;
public class Test03 {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.print("삼각형 높이 : ");
int a = scan.nextInt();
for (int k = 1; k <= a; k++) {
for (int i = 1; i <= a-k; i++) { //1.a가 4 라고치면 처음시작에 공백이 3칸이생기는거 루프끝나면 밑에 for문으로감
//3. 두번쨰루프에서 공백 2칸 세번째루프 공백 1 칸 마지막(4) 루프 공백0칸
System.out.print("-");
}
for (int j = 1; j <= (k*2)-1; j++){ //2.공백 3칸 후 별 하나찍기
//3. 공백 2칸 후 별3개 ,공백 1칸 후 별5개 , 별7개
System.out.print("*");
}
System.out.println("");
}
}
}
///////////////////////////////////////////
삼각형 높이 : 5
----*
---***
--*****
-*******
*********
이문제는 처음엔되게 어렵게생각하고 있었지만
공백 루프
별 루프를 따로 두어 이중for문이 아닌
위에 for문이 끝나면 밑에for문이 돌아가게끔 생각을 했다..
저렇게 문제에 적어둔것처럼 공백의 수와 별의 수를 각각 적어두니 법칙이보였다
Exam03_reverse
위에 별 피라미드를 거꾸로!!!!!
이렇게 차분하게 공백 의 수 별 등을 차분히 적어서 생각을 해내자
괄호 안의 법칙은 내가생각해낸것임
package chap4.hardEx;
import java.util.Scanner;
public class Test03_2 {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.print("삼각형 높이 : ");
int h = scan.nextInt();
for (int i = h; i >= 1; i--) {
for (int b = 1; b <= h-i; b++) {
System.out.print(" ");
}
for (int c = 1; c <= (i*2)-1; c++) {
System.out.print("*");
}System.out.println();
}
}
}
///////////////////////////////////////
삼각형 높이 : 6
***********
-*********
--*******
---*****
----***
-----*