on
java 수업 2일차_반복문
java 수업 2일차_반복문
1. for문, 이중 for문
public class ForFor { public static void main(String[] args) { for(int i = 0; i < 10 ;i++){ System.out.print(i+" "); } System.out.println(""); for (int i = 1; i < 10; i++) { for (int j = 1; j < 10; j++) { System.out.print(i + " * " + j + " = " + i * j + "\t"); } System.out.println(""); } } }
2. while문, while 반복문으로 평균 구하기
import java.util.Scanner; public class While { public static void main(String[] args) { // 순서가 있으면 for문, 없으면 while문 씀 int num01 = 10; int i = 0; while(i
3. do-while문, 알파벳 출력
public class DoWhile { public static void main(String[] args) { //a~z 까지 출력 char ch = 'a'; do { System.out.println("우선 한번 실행, 조건이 맞으면 반복문 종료"); System.out.print(ch); //순서 중요 ch = (char)(ch+1); //글자 값을 하나씩 증가시킴 } while(ch <= 'z'); } }
>> 알파벳은 컴퓨터에 순서대로 값이 저장되어 있음. 1만큼의 간격차가 있어 'ch+1'이 다음 알파벳을 나타낼 수 있음
4. continue (반복문 건너뛰기), 양수값만 더하기
import java.util.Scanner; public class Continue { public static void main(String[] args) { // 정수 다섯개 입력 받아서 합 구하기 System.out.println("점수 5개를 입력하면 양수의 합만 구합니다."); Scanner scan = new Scanner(System.in); int sum = 0; for (int i = 0; i < 5; i++) { System.out.println("점수를 입력하세요>>"); int num = scan.nextInt(); if (num <= 0) continue;// break는 반복문 믈럭 빠져나가기, continue는 건너뛰기 sum += num; } System.out.println("총 합은: " + sum); }
5. break (반복문 빠져나가기), 문자 입력받기, 문자 비교하기
import java.util.Scanner; public class Break { public static void main(String[] args) { Scanner scan = new Scanner(System.in); //홍길동을 입력했는지 판단 String txt01 = scan.next(); // 이어진 글자만 인식 if (txt01.equals("홍길동")) {// 문자의 비교는 .equals() 사용 System.out.println("스트링은 이퀄"); } //exit을 입력하면 반복문 빠져나가기 while (true) { System.out.println(">> "); String txt02 = scan.nextLine(); // 한 줄 인식 if (txt02.equals("exit")) break; } System.out.println("종료합니다."); scan.close(); } }
>> scan.next() : 붙어있는 첫부분 단어 입력, 띄어쓰기 이후는 입력 X
>> .equals() : 문자 비교해서 같으면 true, 틀리면 false
from http://mol-gga.tistory.com/18 by ccl(A) rewrite - 2021-12-27 13:27:53