printf("%c의 블로그", 'Molkka');

코딩공부/JAVA

[java] 반복문

mol_kka 2021. 12. 27. 13:21

 

 

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<num01) 
			System.out.println("나는 10보다 작을때까지 뭔가를 수행하는 while입니다.");
			i++; //반드시 반복문을 빠져나갈 수 있는 조건을 만들어줘야 함.
		}

		// 정수를 여러개 입력받아서 평균을 구하라. -1을 입력하면 종료된다.
		Scanner scan = new Scanner(System.in);
		System.out.println("점수를 입력하시오. 마지막에 -1을 입력하면 평균을 보여드립니다.");
		int sum = 0;
		int num02 = scan.nextInt();
		while (num02 != -1) {
			System.out.println("나는 -1을 입력받을 때까지 계속 일을 수행하는 while 입니다.");
			sum += num02;
			i++;
			num02 = scan.nextInt();
		}
		System.out.println("당신은 " + i + "개 입력하였고 평균은 " + sum / i + "입니다.");
		scan.close();
	}

}

 

 

 

 

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