for문을 이용하여 1에서 10까지의 덧셈으로 표시하고 합을 출력하라.
public class ForSample {
public static void main(String[] args) {
int sum=0;
for(int i=1; i<11; i++){
sum+=i;
System.out.print(i);
if(i<10){
System.out.print("+");
} else {
System.out.print("="+sum);
}
}
}
}
1+2+3+4+5+6+7+8+9+10=55
while문은 반복 횟수를 알지 못하는 경우에 이용된다고 했다. while문을 이용하여 -1이 입력될 때까지 정수를 계속 입력받아 합을 구하고 평균을 출력하는 프로그램을 작성하라.
import java.util.Scanner;
public class WhileSample {
public static void main(String[] args) {
int count=0; //입력받은 정수의 개수
int sum=0;
Scanner sc = new Scanner(System.in);
System.out.println("정수를 입력하고 마지막에 -1을 입력하세요.");
int n = sc.nextInt();
while (n!=-1){
sum += n;
count++;
n = sc.nextInt();
}
if(count==0){
System.out.println("입력받은 정수가 없습니다.");
} else {
System.out.print("정수의 개수는 "+count+"개이며 ");
System.out.println("평균은 "+(double)sum/count+"입니다.");
}
sc.close();
}
}
정수를 입력하고 마지막에 -1을 입력하세요.
3
2
9
-1
정수의 개수는 3개이며 평균은 4.666666666666667입니다.
do-while문을 이용하여 'a'부터 'z'까지 출력하는 프로그램을 작성하라.
public class DoWhileSample {
public static void main(String[] args) {
char c = 'a';
do {
System.out.print(c);
c=(char)(c+1);
} while (c<='z');
}
}
abcdefghijklmnopqrstuvwxyz
2중 중첩 for문을 사용하여 구구단을 출력하는 프로그램을 작성하라.
한 줄에 한 단씩 출력한다.
public class NestedLoop {
public static void main(String[] args) {
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();
}
}
}
1*1=1 1*2=2 1*3=3 1*4=4 1*5=5 1*6=6 1*7=7 1*8=8 1*9=9
2*1=2 2*2=4 2*3=6 2*4=8 2*5=10 2*6=12 2*7=14 2*8=16 2*9=18
3*1=3 3*2=6 3*3=9 3*4=12 3*5=15 3*6=18 3*7=21 3*8=24 3*9=27
4*1=4 4*2=8 4*3=12 4*4=16 4*5=20 4*6=24 4*7=28 4*8=32 4*9=36
5*1=5 5*2=10 5*3=15 5*4=20 5*5=25 5*6=30 5*7=35 5*8=40 5*9=45
6*1=6 6*2=12 6*3=18 6*4=24 6*5=30 6*6=36 6*7=42 6*8=48 6*9=54
7*1=7 7*2=14 7*3=21 7*4=28 7*5=35 7*6=42 7*7=49 7*8=56 7*9=63
8*1=8 8*2=16 8*3=24 8*4=32 8*5=40 8*6=48 8*7=56 8*8=64 8*9=72
9*1=9 9*2=18 9*3=27 9*4=36 9*5=45 9*6=54 9*7=63 9*8=72 9*9=81
5개의 정수를 입력받고 그 중 양수들만 합하여 출력하는 프로그램을 작성하라.
입력된 수가 0이나 음수이면 continue문을 이용하여 합하지 않고 다음 반복으로 넘어간다.
import java.util.Scanner;
public class ContinueExample {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("정수 5개를 입력하세요.");
int sum=0;
for(int i=0; i<5; i++) {
int n = sc.nextInt();
if(n<=0) continue;
else sum+=n;
}
System.out.println("양수의 합은 "+sum);
sc.close();
}
}
정수 5개를 입력하세요.
3
-1
3
0
2
양수의 합은 8
"exit"이 입력되면 while문을 벗어나도록 break문을 활용하는 프로그램을 작성하라.
import java.util.Scanner;
public class BreakExample {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("exit을 입력하면 종료됩니다.");
while (true) {
System.out.print(">>");
String text = sc.nextLine();
if(text.equals("exit")) {
break;
}
}
System.out.println("종료합니다");
sc.close();
}
}
exit을 입력하면 종료됩니다.
>>edit
>>exit
종료합니다
양수 5개를 입력받아 배열에 저장하고, 제일 큰 수를 출력하는 프로그램을 작성하라.
import java.util.Scanner;
public class ArrayAccess {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int intArray[] = new int[5]; //배열 생성
int max=0; //현재 최대값
System.out.println("양수 5개를 입력하세요.");
for(int i=0; i<5; i++){
intArray[i]=sc.nextInt();
if(intArray[i]>max)
max=intArray[i];
}
System.out.print("가장 큰 수는 "+max+"입니다.");
sc.close();
}
}
양수 5개를 입력하세요.
1
3
2
9
6
가장 큰 수는 9입니다.
배열의 length 필드를 이용하여 배열 크기만큼 정수를 입력받고 평균을 구하는 프로그램을 작성하라.
import java.util.Scanner;
public class ArrayLength {
public static void main(String[] args) {
int intArray[] = new int[5];
int sum=0;
Scanner sc = new Scanner(System.in);
System.out.print(intArray.length+"개의 정수를 입력하세요>> ");
for(int i=0; i< intArray.length; i++) {
intArray[i]=sc.nextInt();
}
for(int i=0; i< intArray.length; i++) {
sum += intArray[i];
}
System.out.println("평균은 "+(double)sum/ intArray.length);
sc.close();
}
}
import java.util.Scanner;
public class ArrayLengthFor {
public static void main(String[] args) {
int intArray[] = new int[5];
int sum=0;
Scanner sc = new Scanner(System.in);
System.out.print(intArray.length+"개의 정수를 입력하세요>> ");
for(int i=0; i< intArray.length; i++) {
intArray[i]=sc.nextInt();
sum += intArray[i];
}
System.out.println("평균은 "+(double)sum/ intArray.length);
sc.close();
}
}
5개의 정수를 입력하세요>> 1 2 3 4 8
평균은 3.6
for-each문을 활용하는 사례를 보자.
public class ForEachEx {
enum Week { 월, 화, 수, 목, 금, 토, 일 }
public static void main(String[] args) {
int n[] = {1,2,3,4,5};
String names[] = {"사과", "배", "바나나", "딸기", "체리", "포도"};
int sum=0;
//k는 n[0], n[1], ..., n[4] 표현
for(int k:n){
System.out.print(k+" ");
sum += k;
}
System.out.println("합은 "+sum);
//s는 names[0], names[1], ..., names[5] 표현
for(String s:names){
System.out.print(s+" ");
}
System.out.println(" ");
//day는 월, 화, 수, 목, 금, 토, 일 반복
for(Week day:Week.values()){
System.out.print(day+"요일 ");
}
System.out.println(" ");
}
}
1 2 3 4 5 합은 15
사과 배 바나나 딸기 체리 포도
월요일 화요일 수요일 목요일 금요일 토요일 일요일
2차원 배열에 학년별로 1, 2학기 성적으로 저장하고, 4년간 전체 평점 평균을 출력하라.
public class ScoreAverage {
public static void main(String[] args) {
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));
}
}
4년 전체 평점 평균은 3.725
다음 그림과 같은 비정방형 배열을 만들어 값을 초기화하고 출력하라.
|10|11|12|
|20|21|
|30|31|32|
|40|41|
public class SkewedArray {
public static void main(String[] args) {
int intArray[][] = new int[4][];
intArray[0] = new int[3];
intArray[1] = new int[2];
intArray[2] = new int[3];
intArray[3] = new int[2];
for(int i=0; i<intArray.length; i++) {
for(int j=0; j<intArray[i].length; j++)
intArray[i][j] = (i+1)*10+j;
}
for(int i=0; i<intArray.length; i++) {
for(int j=0; j<intArray[i].length; j++)
System.out.print(intArray[i][j]+" ");
System.out.println();
}
}
}
public class SkewedArrayFor {
public static void main(String[] args) {
int intArray[][] = new int[4][];
intArray[0] = new int[3];
intArray[1] = new int[2];
intArray[2] = new int[3];
intArray[3] = new int[2];
for(int i=0; i<intArray.length; i++) {
for(int j=0; j<intArray[i].length; j++) {
intArray[i][j] = (i + 1) * 10 + j;
System.out.print(intArray[i][j] + " ");
}
System.out.println();
}
}
}
10 11 12
20 21
30 31 32
40 41
정수 4개를 가지는 일차원 배열을 생성하고 1,2,3,4로 초기화한 다음, 배열을 리턴하는 makeArray()를 작성하고, 이 메소드로부터 배열을 전달받아 값을 출력하는 프로그램을 작성하라.
public class ReturnArray {
static int[] makeArray() {
int temp[] = new int[4];
for(int i=0; i<4; i++) {
temp[i]=i;
}
return temp;
}
public static void main(String[] args) {
int intArray[];
intArray = makeArray();
for(int i=0; i< intArray.length; i++) {
System.out.print(intArray[i]+" ");
}
}
}
0 1 2 3
사용자가 명령행에 입력한 실수들을 main() 메소드에서 전달받아 합을 구하는 프로그램을 작성하라.
public class Calc {
public static void main(String[] args) {
double sum=0;
for(int i=0; i<args.length; i++) {
sum += Double.parseDouble(args[i]);
}
System.out.println("sum = "+sum);
}
}
두 정수를 입력받아 나눗셈을 하고 몫을 구하는 프로그램 코드이다. 사용자가 나누는 수에 0을 입력하면 ArithmeticException 예외가 발생하여 프로그램이 강제 종료된다.
import java.util.Scanner;
public class DivideByZero {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("나뉨수를 입력하시오:");
int dividend = sc.nextInt();
System.out.print("나눗수를 입력하시오:");
int divisor = sc.nextInt();
System.out.println(dividend+"를 "+divisor+"로 나누면 몫은 "+dividend/divisor+"입니다.");
sc.close();
}
}
나뉨수를 입력하시오:3
나눗수를 입력하시오:0
Exception in thread "main" java.lang.ArithmeticException: / by zero
at ch3.ex.DivideByZero.main(DivideByZero.java:13)
try-catch 블록을 이용하여 예제 3-14를 수정하여, 정수를 0으로 나누는 경우에 "0으로 나눌 수 없습니다."를 출력하고 다시 입력 받는 프로그램을 작성하라.
import java.util.Scanner;
public class DivideByZeroHandling {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
while (true) {
System.out.print("나뉨수를 입력하시오:");
int dividend = sc.nextInt();
System.out.print("나눗수를 입력하시오:");
int divisor = sc.nextInt();
try {
System.out.println(dividend+"를 "+divisor+"로 나누면 몫은 "+dividend/divisor+"입니다.");
break;
} catch (ArithmeticException e) {
System.out.println("0으로 나눌 수 없습니다! 다시 입력하세요");
}
}
sc.close();
}
}
나뉨수를 입력하시오:20
나눗수를 입력하시오:0
0으로 나눌 수 없습니다! 다시 입력하세요
나뉨수를 입력하시오:20
나눗수를 입력하시오:4
20를 4로 나누면 몫은 5입니다.
배열의 인덱스가 범위를 벗어날 때 발생하는 ArrayIndexOutOfBoundException을 처리하는 프로그램을 작성하라.
public class ArrayException {
public static void main(String[] args) {
int[] intArray = new int[5];
intArray[0] = 0;
try {
for(int i=0; i<5; i++) {
intArray[i+1]=i+1+intArray[i]; //i=4인 경우 예외 발생
System.out.println("intArray["+i+"]="+intArray[i]);
}
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("배열의 인덱스가 범위를 벗어났습니다.");
}
}
}
intArray[0]=0
intArray[1]=1
intArray[2]=3
intArray[3]=6
배열의 인덱스가 범위를 벗어났습니다.
3개의 정수를 입력받아 합을 구하는 프로그램을 작성하라. 사용자가 정수가 아닌 문자를 입력할 때 발생하는 InputMismatchException 예외를 처리하여 다시 입력받도록 하라.
import java.util.InputMismatchException;
import java.util.Scanner;
public class InputException {
public static void main(String[] args) {
int sum=0, n=0;
Scanner sc = new Scanner(System.in);
System.out.println("정수 3개를 입력하세요.");
for(int i=0; i<3; i++){
System.out.print(i+">>");
try {
n = sc.nextInt();
} catch (InputMismatchException e) {
System.out.println("정수가 아닙니다. 다시 입력하세요!");
sc.nextLine();
i--;
continue;
}
sum+=n;
}
System.out.println("합은 "+sum);
sc.close();
}
}
정수 3개를 입력하세요.
0>>3
1>>2
2>>하이
정수가 아닙니다. 다시 입력하세요!
2>>2
합은 7
문자열을 정수로 변환할 때 발생하는 NumberFormatException을 처리하는 프로그램을 작성하라.
public class NumException {
public static void main(String[] args) {
String stringNumber[] = {"23","12","3.141592","998"};
int i=0;
try {
for(i=0; i<stringNumber.length; i++){
int j = Integer.parseInt(stringNumber[i]);
System.out.println("정수로 변환된 값은 "+j);
}
} catch (NumberFormatException e) {
System.out.println(stringNumber[i]+"는 정수로 변환할 수 없습니다.");
}
}
}
정수로 변환된 값은 23
정수로 변환된 값은 12
3.141592는 정수로 변환할 수 없습니다.