Lab1 Review

Lab1_Review

import java.util.Scanner;

class Arithmetic {
public static int add(int n, int m) {
return n + m;
}

public static int divide(int n, int m) throws ArithmeticException {
return n / m;
}
}

public class Lab1 {

// 5.1 Scanner, user input
static int input1, input2;
static Scanner scan = new Scanner(System.in);
public static void getUserInput()
{
System.out.print(“Please enter [input1]: “);
input1 = scan.nextInt();
System.out.print(“Please enter [input2]: “);
input2 = scan.nextInt();
scan.nextLine();
}
// 5.2 get ‘q’-key
public static boolean getUserExitKey() {
System.out.print(“Press q-key to exit the program or enter-key to enter new user input: “);
String s = scan.nextLine();
if (s.contentEquals(“q”))
return true;
else
return false;
}

// 2. method 정의
static int add(int i, int j) {
int k = i + j;
return k;
}

public static void main(String[] args) {
// TODO Auto-generated method stub

// println
System.out.println(“test”);

// 0. String +
String a = “1”;
String b = “2”;
String c = a + b;
System.out.println(“a=” + a);
System.out.println(“b=” + b);
System.out.println(“c=” + c);

// 1. command line arguments
if (args.length == 3) {
System.out.println(args[0]);
System.out.println(args[1]);
System.out.println(args[2]);
}

// 2.1 method를 사용하지 않는다면 아래 코드 부분이 반복적으로 사용되어야 함
int i = 1; // local variable
int j = 2; // local variable
int k = i + j; // local variable
System.out.println(“i=” + i);
System.out.println(“j=” + j);
System.out.println(“k=” + k);

i = 10;
j = 20;
k = i + j;
System.out.println(“i=” + i);
System.out.println(“j=” + j);
System.out.println(“k=” + k);

i = 100;
j = 200;
k = i + j;
System.out.println(“i=” + i);
System.out.println(“j=” + j);
System.out.println(“k=” + k);

// 2.2 method 사용
int k2 = add(1, 2);
System.out.println(“k2=” + k2);
k2 = add(10, 20);
System.out.println(“k2=” + k2);
k2 = add(i, j);
System.out.println(“k2=” + k2);

// 3. class 사용
int k3 = Arithmetic.add(1, 2);
System.out.println(“k3=” + k3);
k3 = Arithmetic.add(10, 20);
System.out.println(“k3=” + k3);
k3 = Arithmetic.add(i, j);
System.out.println(“k3=” + k3);

// 4. for-loop 사용
for (int n=0; n<10; n++) {
int k4 = Arithmetic.add(n, n*2);
System.out.println(“k4[” + n + “]=” + k4);
}

// 5.1 Scanner 클래스 사용 사용자 입력
System.out.println(“두 수를 입력하여 덧셈을 합니다”);
getUserInput();
int k5 = Arithmetic.add(input1, input2);
System.out.println(“k5=” + k5);

// 5.2 do-while-loop 사용
System.out.println(“\n\n”);
do {
getUserInput();
int k6 = Arithmetic.add(input1, input2);
System.out.println(“k6=” + k6);
} while (!getUserExitKey());

// 5.3 try/catch/throws
try {
System.out.println(“두 수를 입력하여 나눗셈을 합니다”);
getUserInput();
int k7 = Arithmetic.divide(input1, input2);
System.out.println(“k7=” + k7);
} catch (ArithmeticException e) {
e.printStackTrace();
}

System.out.println(“done”);
}
}