✨
Java
  • 자바의 역사
  • Ch1
    • Before Start Java
      • History of Java
      • Feature of Java
      • API Documentation
      • Hello World!
      • eclipse shortcut
      • Eclipse IDE
      • GitHub to eclipse
  • Ch2
    • Variable
      • Variable
    • Variable Type
    • Character and String
    • Primitive type and range
    • printf and formatter
    • Scanner
    • Overflow of Int
    • Transition between different variable types
    • Object Array
  • CH3
    • Operator
  • CH4
    • 조건문과 반복문
    • if statement
    • switch
    • Math.random()
    • for statement
    • while statement
    • break, continue, named iterated statement
  • CH5
    • Array
    • 배열 활용
    • String Array
  • OOP
    • Intro
  • Class and Object
  • Make multiple Classes in one file
  • How to use Object
  • Object Array
  • Variable type according to declared location
  • Class Variable and Instance Variable
  • Method
  • Call Stack
  • Parameter
  • Static method(Class method) and Instance method
  • (Method)Overloading
  • Constructor
  • Constructor this()
  • Reference type variable "this"
  • Initialize variable
  • Inheritance
  • Composite
  • Single Inheritance, Object Class
  • (Method)Overriding
  • super, super()
  • package, class path
  • import, static import
  • modifier
  • access modifier
  • Encapsulation
  • Polymorphism
  • reference type transition
  • instanceof operator
  • Parameter polymorphism
  • Multiple object using one array
  • Abstract Class, Abstract Method
  • Creating Abstract Class
  • Interface
  • Interface Polymorphism
  • Interface Pros
  • Default method and static method
  • Inner Class
  • Anonymous Class
  • java.lang package and useful class
    • Object class
    • hashCode(), toString()
    • String class
    • StringBuffer class
    • StringBuilder class
    • Math class
    • Wrapper class
    • Number class
    • String to Number, String to Wrapper class
    • Auto-boxing and (auto)Unboxing
  • Collection Framework
    • Collections framework
    • List, Set, Map Interface
    • List의 removeAll() 과 clear() 비교
    • List Interface - ArrayList
    • How to view Java API source
    • List Interface - LinkedList
    • Stack and Queue
    • Iterator, ListIterator, Enumeration
    • Array
    • Comparator와 Comparable
    • Stack
    • String
    • String + char = String
    • String.toCharArray()
    • BufferedReader / BufferWriter
    • Scanner로 String 입력 - next( )와 nextLine( )
    • 공백없이 2차원배열 데이터 String으로 한번에 한줄씩 입력받기(문자/숫자)
    • 공백을 사이에 두고 빠른 2차원 배열 입출력
    • arr[index++]과 arr[index] index++의 차이
    • int와 long의 차이
    • Untitled
    • 타입 간의 변환
    • Array 와 ArrayList
    • valueOf()
    • Char
    • 변수, 객체 초기화(초기값 설정)
  • error troubleshooting
    • No enclosing instance of type
    • ASCII Code Table
    • java.lang.NumberFormatException
    • No enclosing instance..
  • reference
    • String을 생성하는 2가지 방법과 차이점
    • StackOverflowError(스택, 힙 메모리)
    • swtich-case 반복문
Powered by GitBook
On this page

Was this helpful?

  1. CH4

break, continue, named iterated statement

break문과 continue문을 썼을 때 실행 흐름을 보여준다.

String tmp = scanner.nextLine();
int menu = Integer.parseInt(tmp);

while(true) {
    System.out.println("(1) Square");
    System.out.println("(2) Square root");
    System.out.println("(3) Log");
    System.out.print("원하는 메뉴(1~3)을 선택하세요.(종료:0)");
    
    //예외상황들을 먼저 처리
    if(menu == 0) {
        System.out.prinln("프로그램을 종료합니다.");
        break;//while문을 탈출!!!
    } else if( !(1 <= menu && menu <= 3)) {
        System.out.println("메뉴를 잘못 선택하셨습니다.(종료는0);
        continue;//아래의 출력문을 실행하지 않고 계속한다!
    }
    
    System.out.println("선택하신 메뉴는" + menu + "번입니다.");
}

이름 붙은 반복문

: 반복문에 이름을 붙여서 하나 이상의 반복문을 벗어날 수 있다.

Loop1 : for(int i=2; i <=9; i++) {
    for(int j = 1; j <=9; j++) {
        ...
        break Loop1;//'Loop1'이라고 명명한 반복문 탈출! 
        break;//현재의 for문만 탈출
    }
}

반복문에 이름을 붙여 제곱과 제곱근, 로그를 구하는 코드를 작성해보자.

알고리즘의 구조

전체 프로그램을 구성하는 부분과 프로그램 내부에서 각각 1,2,3번을 선택했을 때 하는 동작을 구성하는 부분 이렇게 2가지로 나눌 수 있겠다.

  1. 전체 프로그램 구성 : 메뉴 출력 반복문으로 구현. 0을 눌렀을 때 break문으로 현재 반복문(outer while문)을 탈출하여 프로그램 종료 가능. 예외상황 처리-1~3 사이 번호가 아닐 때.

  2. 1,2,3번 입력받았을 때 동작 구현 : 1/2/3번을 을 때, num을 입력받아 제곱값/제곱근/로 제공. 99번을 받으면 전체 프로그램 종료기 때문에 break outer;를 통해 outer 반복문을 탈출하여 전체 프로그램 종료한다. 기능 구현 후에는 현재 반복문을 탈출하여 프로그램 메뉴로 다시 돌아가도록 한다.

import java.util.*;

class calculator {
	public static void main(String[] args) {
		int menu = 0, num = 0;
		Scanner scanner = new Scanner(System.in);
		
		outer://아래의 while문에 이름을 붙여준다.
		while(true) {
			System.out.println("(1) square");
			System.out.println("(2) square root");
			System.out.println("(3) log");
			System.out.print("원하는 메뉴(1~3)를 선택하세요.(계산 종료:0, 전체 종료:99)>");
			
			String tmp = scanner.nextLine();
			menu = Integer.parseInt(tmp);
			
			if(menu == 0) {
//				System.out.println("프로그을 종료합니다.");
				break;
			}else if(!(1 <= menu && menu <= 3)) {
				System.out.println("메뉴를 잘못 선택하셨습니다.(종료는0)");
				continue;//아래의 코드들을 실행하지 않고 넘어간다.
			}
			
			//계산을 하는 부분.일종의 함수를 호출하여 실행하고, 실행한 다음에는 break문으로 종료하는.
			for(;;) {//무한반복문을 의미하는 for
				System.out.print("계산할 값을 입력하세요.(계산 종료:0, 전체 종료:99)>");
				tmp = scanner.nextLine();
				num = Integer.parseInt(tmp);
				
				if(num == 0) {
					break;//계산 종료. 현재의 for문만 탈출! 
				}
				if(num == 99) {
					break outer;//전체 종료. 현재의 for문과 while문을 모두 탈출! 
				}
				switch(menu) {
				case 1:
					System.out.println("result="+num*num);
					break;
				case 2:
					System.out.println("result="+Math.sqrt(num));
					break;
				case 3:
					System.out.println("result="+Math.log(num));
					break;
				}
			}//for문 끝 
		}//while문 끝 
		System.out.println("프로그램을 종료합니다!");
	}
}

Previouswhile statementNextArray

Last updated 4 years ago

Was this helpful?