3.1 반복문
for(초기문; 조건식; 반복 후 작업;) {
~~~~
}
조건식에는 논리변수나 논리 연산을 사용, true를 쓰거나 비워두면 무한반복함
초기문에는 지역변수를 선언하고 바로 사용가능
반복 후 작업문에는 ,로 분리하여 여러문장 사용 가능
조건식이 없으면 컴파일오류 발생
조건식 없으면 컴파일 오류, 작업문 실행 후 반복 조건 따짐
TIP)
반복의 횟수나 범위가 명확한 경우에는 for문을 많이 사용하고
반복횟수를 처음부터 알수없고 반복이 진행되면서 조건식의 결과가 달라지는 경우에는 while이나 do-while
3.2 continue & break
continue는 반복문을 빠져나가지않으면서 즉시 다음 반복으로 넘어가고자 할떄 사용
for문에서는 반복후 작업문으로 while이나 do-while에서는 조건식을 검사함
break는 하나의 반복문을 즉시 벗어날 때 사용
3.3 자바의 배열
인덱스와 인덱스에 대응하는 일련의 데이터들로 이루어진 연속적인 자료구조
int intArray[]; or int [] intArray;
선언 시 []안에 배열의 크기 지정하면 안됨
intArray=new int[5]
=> 1,2 한번에 하면 int intArray[]=new int[5];
배열 선언문에서 {}에 원소를 나열하여 초기화된 배열을 만들 수 있다.
배열의 인덱스는 정수만 가능 0부터 시작
배열이 생성되있지 않을때 사용 X 음수 인덱스 X
배열이 복사되는 것이 아닌 레퍼런스가 복사되어 배열을 공유하게 됨
배열이 생성되면 length 필드가 배열 객체 내에 생성됨
배열이나 나열의 크기만큼 루프를 돌면서 각 원소를 순차적으로 접근하는데 쓰임
ex)
for(int k : n) {
~~ // 반복될 때마다 k는 n[0], n[1], ~~로 번갈아 설정
3.4 다차원 배열
2차원 배열

3.5 메소드의 배열 리턴
메소드는 배열에 대한 레퍼런스를 리턴하고 메소드의 리턴타입에 배열의 크기를 지정하지않음
3.6 자바의 예외 처리
예외? 실행 중 오동작이나 결과에 악영향을 미치는 예상치 못한 상황 발생
응용프로그램에 예외에 대처하는 코드가 없으면 자바플랫폼이 응용프로그램을 강제로 종료시킴
try-catch-finally문으로 예외처리함
catch()의 ()안에 int, double과 같은 기본 타입 사용 불가

자바의 예외클래스

예제 3-1
public class ForSample {
public static void main(String[] args) {
// TODO Auto-generated method stub
int i, sum=0;
for (i=1; i<=10; i++) {
sum+=i; //i가 증가하면서 sum에 추가
System.out.print(i);
if (i<=9) {
System.out.print("+");
}
else {
System.out.print("=");
System.out.print(sum);
}
}
}
}
예제 3-2
import java.util.Scanner;
public class WhileSample {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner scanner;
scanner = new Scanner(System.in);
int count=0, n=0;
double sum=0;
System.out.println("정수를 입력하고 마지막에 0을 입력하세요.");
while ((n=scanner.nextInt())!=0) {
sum=sum+n;
count++;
}
System.out.print("수의 개수는 "+count+"개이며 ");
System.out.println("평균은 "+sum/count+"입니다.");
scanner.close();
}
}
예제 3-3
public class DoWhileSample {
public static void main(String[] args) {
// TODO Auto-generated method stub
char a='a';
do {
System.out.print(a);
a=(char)(a+1);
} while (a<='z');
}
}
예제 3-4
public class NestedLoop {
public static void main(String[] args) {
// TODO Auto-generated method stub
for (int i=1; i<10; i++) {
for (int j=1; j<10; j++) {
System.out.print(i+"*"+j+"="+i*j);
System.out.print('\t');
}
System.out.println();
}
}
}
예제 3-5
import java.util.Scanner;
public class ContinueExample {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner scanner = new Scanner(System.in);
System.out.println("정수를 5개 입력하세요.");
int sum=0;
for (int i=0; i<5; i++) {
int n=scanner.nextInt();
if (n<=0)
continue;
else
sum+=n;
}
System.out.println("양수의 합은 "+sum);
scanner.close();
}
}
예제 3-6
import java.util.Scanner;
public class BreakExample {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner scanner=new Scanner(System.in);
System.out.println("exit을 입력하면 종료됩니다.");
while (true) {
System.out.print(">>");
String text=scanner.nextLine(); //스트링 입력
if(text.equals("exit"))
break;
}
System.out.println("종료합니다...");
scanner.close();
}
}
예제 3-7
import java.util.Scanner;
public class ArrayAccess {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner scanner=new Scanner(System.in);
int intArray[];
intArray=new int[5];
int max=0;
System.out.println("양수 5개를 입력하세요");
for (int i=0; i<5; i++) {
intArray[i]=scanner.nextInt();
if (intArray[i]>max)
max=intArray[i];
}
System.out.print("가장 큰 수는 "+max+"입니다.");
scanner.close();
}
}
예제 3-8
import java.util.Scanner;
public class ArrayLength {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner scanner=new Scanner(System.in);
System.out.println("5개의 정수를 입력하세요");
int intArray[]=new int[5]; //배열 생성과 선언
double sum=0.0;
for(int i=0; i<intArray.length; i++)
intArray[i]=scanner.nextInt();
for(int i=0; i<intArray.length; i++)
sum+=intArray[i];
System.out.print("평균은 "+sum/intArray.length);
scanner.close();
}
}
예제 3-9
public class foreachEx {
public static void main(String[] args) {
// TODO Auto-generated method stub
int [] n = {1,2,3,4,5};
int sum=0;
for(int k:n ) { //k는 n[0], n[1], ... n[4]
System.out.print(k+" ");
sum+=k;
}
System.out.println("합은 "+sum);
String f[]= {"사과","배","체리","딸기","포도"};
for(String s:f)
System.out.print(s+" ");
}
}
예제 3-10
public class ScoreAverage {
public static void main(String[] args) {
// TODO Auto-generated method stub
double score[][]= {{3.3, 3.4},
{3.5, 3.6},
{3.7, 4.0},
{4.1, 4.2}};
double sum=0;
for(int year=0; year<score.length; year++)
for(int term=0; term<score[year].length; term++)
sum+=score[year][term];
int n=score.length; //4
int m=score[0].length; //2
System.out.println("4학년 전체의 평균은 "+sum/(n*m));
}
}
예제 3-11
public class ReturnArray {
static int[] makeArray() {
int temp[]=new int[4];
for(int i=0; i<temp.length; i++)
temp[i]=i;
return temp;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
int intArray[];
intArray=makeArray();
for(int i=0; i<intArray.length; i++)
System.out.print(intArray[i]+" ");
}
}
예제 3-12,13
import java.util.Scanner;
public class DivideByZero {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner scanner=new Scanner(System.in);
int dividend; //나뉨수
int divisor; //나눗수
System.out.print("나뉨수를 입력하세요:");
dividend=scanner.nextInt();
System.out.print("나눗수를 입력하세요:");
divisor=scanner.nextInt();
try {
System.out.println(dividend+"를 "+divisor+"로 나누면 몫은 "+dividend/divisor+"입니다.");
}
catch(ArithmeticException e) {
System.out.println("0으로 나눌 수 없습니다."); //ArithmeticException e는 0으로 나눴을때 예외 처리 코드
}
finally {
scanner.close();
}
}
}
예제 3-14
import java.util.InputMismatchException;
import java.util.Scanner;
public class InputException {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner scanner=new Scanner(System.in);
System.out.println("정수 3개를 입력하세요");
int sum=0, n=0;
for (int i=0; i<3; i++) {
System.out.print(i+">>");
try {
n=scanner.nextInt();
}
catch (InputMismatchException e) {
System.out.println("정수가 아닙니다. 다시 입력하세요.");
scanner.next(); //정수가 아닌 입력값을 버린다.
i--;
continue;
}
sum+=n;
System.out.println("합은 "+sum);
scanner.close();
}
}
}