반응형

1. 범위를 벗어난 배열의 접근 

오류 메세지 

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 3

 

코드 

public class DEMO {
	public static void main(String[] args) {
		int [] array = { 0, 1, 2, };
		
		System.out.println(array[3]);
	}
}

 배열의 크기가 3이고 배열이 0부터 시작하기 때문에 배열 3칸은 없음.

 

2. 0으로 나눌때 발생하는 ArithmeticException 예외

public class Demo2 {
	public static void main(String[] args) {
		int [] aa = new int[3];
		try {
			aa[2] = 100/0;
			aa[3] = 100;
		}catch (ArrayIndexOutOfBoundsException e) {
			System.out.println("배열 첨자가 배열 크기보다 커요 ~~");
		} catch (ArithmeticException e) {
			System.out.println("0으로 나누는 등의 오류에요~~");
		} finally {
			System.out.println("이 부분은 무조건 나와요 ~~");
		}
	}
	
}
public class Demo3 {
	public static void main(String[] args) {
		int a = 100, b = 0;
		int result;
		try {
			result = a / b;
		} catch (ArithmeticException e) {
			System.out.print("발생 오류 ==>");
			System.out.println(e.getMessage());
		}
	}
}

 결과

발생 오류 ==>/ by zero

3. 예외발생으로 프로그램이 강제 종료되는 경우 

오류 메세지 : Exception in thread "main" java.lang.Error: Unresolved compilation problem: 
Unhandled exception type InterruptedException

package test01;

public class Demo3 {
	public static void main(String[] args) {
		Thread.sleep(100);
	}
}

4. 예외 잡아 처리하기 (범위를 벗어난 배열의 접근 )

try {
	예외가 발생할 수 있는 실행문;
} catch (예외클래스 1 | 예외 클래스 2 변수) {
	핸들러;
}
public class Demo3 {
	public static void main(String[] args) {
		int [] array = { 0 , 1, 2, };
		try { 
			System.out.println("마지막 원소 => " + array[3]);
			System.out.println("첫 번째 원소 => " + array[0]);
		} catch (ArrayIndexOutOfBoundsException e) {
			System.out.println("원소가 존재하지 않습니다. ");
		} 
		System.out.println("어이쿠!!");
	}
}

ArrayIndexOutOfBoundsException : 배열, 벡터 등에서 범위를 벗어난 인덱스를 사용할 때 발생한다.

 

결과

원소가 존재하지 않습니다. 
어이쿠!!

 

반응형

'JAVA > 문법' 카테고리의 다른 글

[JAVA] 인터페이스 구현  (0) 2020.01.04
[JAVA] 추상클래스  (0) 2020.01.04
[JAVA] 클래스  (0) 2019.12.22
[JAVA] 배열 2  (0) 2019.12.15
[JAVA] 배열  (0) 2019.12.15
반응형
package hello;
class Pencil{
	public void write() {
		System.out.println("연필로 쓴다");
	}
}

class Ballpoint{
	public void writing() {
		System.out.println("볼펜으로 쓴다.");
	}
}
public class Mainclass {
	public static void main(String[] args) {
		Pencil pencil = new Pencil();
		Ballpoint ballpoint = new Ballpoint();
		pencil.write();
		ballpoint.writing();
	}
}
package hello;
interface Frindle {
	public void write();
}

class Pencil implements Frindle {
	public void write() {
		System.out.println("연필로 쓴다.");
	}
}

class Ballpoint implements Frindle {
	public void write() {
		System.out.println("볼펜으로 쓴다.");
	}
}

public class Mainclass{
	public static void main(String[] args) {
		Frindle frindle = new Pencil();
		frindle.write();
		Frindle frindle1 = new Ballpoint();
		frindle1.write();
	}
}
package hello;
interface PhoneInterface {
	final int TIMEOUT = 10000;
	void sendCall();
	void receiveCall();
	default void printLogo() {
		System.out.println("** phone **");
	}
}
class SamsungPhone implements PhoneInterface {

	@Override
	public void sendCall() {
		System.out.println("띠리리리링");
		
	}

	@Override
	public void receiveCall() {
		System.out.println("전화가 왔습니다.");
		
	}
	public void flash() {
		 System.out.println("전화기에 불이 켜졌습니다.");
	}
	
}

public class Mainclass {
	public static void main(String[] args) {
		SamsungPhone phone = new SamsungPhone();
		phone.printLogo();
		phone.sendCall();
		phone.receiveCall();
		phone.flash();
	}
}
package hello;
interface Mammal {
	abstract void giveBirth();
}
abstract class Fish {
	void swim() {
		System.out.println("물고기는 헤엄치며 움직입니다.");
	}
}

class Whale extends Fish implements Mammal{
	public void giveBirth() {
		System.out.println("고래는 새끼를 낳습니댜.");
	}
	public void swim() {
		System.out.println("고래는 헤엄치며 움직입니다.");
	}
}
public class Ifpr {
	public static void main(String[] args) {
		Whale w = new Whale();
		w.swim();
		w.giveBirth();
	}
}
package hello;
class OuterClass1 {
	void a() {
		System.out.println("method a");
	}
	void b() {}
}

public class Anonymous {
	public static void main(String[] args) {
		OuterClass1 o = new OuterClass1() {
			void a() {
				System.out.println("새롭게 정의한 익명 클래스의 메서드입니다.");
			}
		};
		o.a();
		OuterClass1 ok = new OuterClass1();
		ok.a();
	}
}
새롭게 정의한 익명 클래스의 메서드입니다.
method a
반응형

'JAVA > 문법' 카테고리의 다른 글

[JAVA] 예외처리  (0) 2020.01.05
[JAVA] 추상클래스  (0) 2020.01.04
[JAVA] 클래스  (0) 2019.12.22
[JAVA] 배열 2  (0) 2019.12.15
[JAVA] 배열  (0) 2019.12.15
반응형

추상클래스 : 몸체가 구성되어 있지 않은 메서드를 가지고 있는 클래스 

즉, 선언되어 있으나 구현 되어 있지 않은 메서드, abstract로 선언함.

 1. 추상클래스는 서브 클래스에서 오버라이딩 하여 구현해야 함.

package hello;

abstract class Car{
	int speed = 0;
	String color;
	void upSpeed(int speed) {
		this.speed += speed;
	}
}
class Sedan extends Car{
}
class Truck extends Car{
}
public class AbstractClassExample{
	public static void main(String[] args) {
		Sedan sedan1 = new Sedan();
		System.out.println("승용차 인스턴스 생성~");
		Truck truck1 = new Truck();
		System.out.println("트럭 인스턴스 생성~");
	}
}
package hello;
abstract class Pokemon{
	
	private String name;
	abstract void attack();
	abstract void sound();
	Pokemon(String name) {
		this.name = name;
	}
	public String getname() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
}
class Pikachu extends Pokemon{
	public Pikachu() {
		super("피카츄"); 
	}
	void attack() {
		System.out.println("전기 공격");
	}
	void sound() {
		System.out.println("피카피카");
	}
}

class Squirtle extends Pokemon{
	public Squirtle() {
		super("꼬북이"); 
	}
	void attack() {
		System.out.println("물 공격");
	}
	void sound() {
		System.out.println("꼬북꼬북");
	}
}

public class Sample{
	public static void main(String[] args) {
		Pikachu s = new Pikachu();
		System.out.println("이 포켓몬의 이름은 : " + s.getname());
		s.attack();
		s.sound();
		Squirtle a = new Squirtle();
		System.out.println("이 포켓몬의 이름은 : " + a.getname());
		a.attack();
		a.sound();
	}
}
package hello;

abstract class Car{ 
	private int speed = 0;
	private String name;
	public Car(String name){
		this.name = name;
	}
	void upSpeed(int speed) {
		 this.speed += speed;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	abstract void work();
}

class Sedan extends Car{
	public Sedan(String name) {
		super(name);
	}
	void work() {
		System.out.println(super.getName() +"가 사람을 태우고 있습니다.");
	}
}
class Truck extends Car{
	public Truck(String name) {
		super(name);
	}
	
	void work() {
		System.out.println(super.getName() + "이 짐을 싣고 있습니다.");
	}
}

public class AbstractMethodExample{
	public static void main(String[] args) {
		Sedan sd = new Sedan("빨간 승용차");
		sd.work();
		Truck tk = new Truck("노란트럭");
		tk.work();
	}
}
package hello;

abstract class Calculator{
	public abstract int add(int a, int b);
	public abstract int subtract(int a, int b);
	public abstract double average(int[] a);
}
public class GoodCalc {
	public int add(int a, int b) {
		return a + b;
	}
	
	public int subtract(int a, int b) {
		return a - b;
	}
	public double average(int[] a) {
		int sum = 0;
		for(int i=0; i<a.length; i++) {
			sum += a[i];
		}
		return sum/a.length;
	}
	
	public static void main(String[] args) {
		GoodCalc a = new GoodCalc();
		System.out.println("2 + 3 = " + a.add(2,3));
		System.out.println("2 - 3 = " + a.subtract(2, 3));
		System.out.println("(2 + 3 + 4)/3 = " + a.average(new int [] {2,3,4}) );
	}
}
반응형

'JAVA > 문법' 카테고리의 다른 글

[JAVA] 예외처리  (0) 2020.01.05
[JAVA] 인터페이스 구현  (0) 2020.01.04
[JAVA] 클래스  (0) 2019.12.22
[JAVA] 배열 2  (0) 2019.12.15
[JAVA] 배열  (0) 2019.12.15
반응형
package hello;
import java.util.Scanner;
public class Test {
  String name;
  String location;
  int age;
  public String getName() {
	  return name;
  }
  public void setName(String name) {
	 this.name = name;
  }
  public int getAge() {
	  return age;
  }
  public void setAge(int age) {
	  this.age = age;
  }
  public String getLocation() {
	  return location;
  }
  public void setLocation(String location) {
	  this.location = location;
  }
  public static void main(String[] arg) {
	  Test ct = new Test();
	  Scanner s = new Scanner(System.in);
	  System.out.print("당신의 이름은 : ");
	  String name = s.next();
	  ct.setName(name);
	  System.out.println(ct.getName() + "님 안녕하세요!");
	  System.out.print("당신의 나이를 입력하세요: ");
	  int age = s.nextInt();
	  ct.setAge(age);
	  System.out.print("당신의 사는 지역을 입력하세요 : ");
	  String location = s.next();
	  ct.setLocation(location);
	  System.out.println(ct.getName() + "님 당신은 " + ct.getLocation()+ "에 사는 " +ct.getAge() + "살입니다.");
	  
  }
}
package hello;

public class HelloJava {
	private String msg;
	public HelloJava() {
		msg = "Hello Java!!";
	}
	public HelloJava(String msg) {
		this.msg = msg;
	}
	public HelloJava(String msg, int option) {
		if(option == 1)
			this.msg = msg;
		else if(option == 2)
			this.msg = msg + ", 안녕하세요? ";
	}
	public void print() {
		System.out.println(msg);
	}
	public String getMsg() {
		return msg;
	}
	public void setMsg(String msg) {
		this.msg = msg;
	}
	
}
package hello;

public class HelloRun {
	public void go() {
		HelloJava hello1 = new HelloJava();
		hello1.print();
		
		HelloJava hello2 = new HelloJava("My Hello Java!! ");
		hello2.print();
		
		HelloJava hello3 = new HelloJava("Hello",2);
		hello3.print();
		
		hello2.setMsg("반갑습니다.!!");
		System.out.println(hello2.getMsg());
	}
	public static void main(String[] args) {
		HelloRun hr = new HelloRun();
		hr.go();
	}
}
package hello;
import java.util.Scanner;
public class Grade {
	private int math;
	private int science;
	private int english;
	public Grade(int math, int science, int english) {
		this.math = math;
		this.science = science;
		this.english = english;
	}
	public int average() {
		return (math + science + english) / 3;
	}
	public static void main(String[] args) {
		Scanner s = new Scanner(System.in);
		System.out.print("점수를 입력하세요 : ");
		int math = s.nextInt();
		int science = s.nextInt();
		int english = s.nextInt();
		Grade me = new Grade(math, science, english);
		System.out.println("평균은 " +  me.average());
	}
}
package hello;

import java.util.Scanner;

class DigitsOpr {
	private int num;

	public void setNum(int x) {
		this.num = x;
	}
	public int countDigits() {
		int n = num;
		int count = 0;
		while(n>0) {
			n/=10;
			count++;
		}
		return count;
	}
}
public class number {
	public static void main(String []args) {
		DigitsOpr dig = new DigitsOpr();
		Scanner sc = new Scanner(System.in);
		int n= sc.nextInt();
		dig.setNum(n);
		System.out.println(n + "은 " + dig.countDigits() + "자리입니다.");
	}
}


package hello;

import java.util.Scanner;

class DigitsOpr{
	private int num;

	public void setNum(int x) {
		this.num = x;
	}
	public boolean isArmstrong() {
		int n, sum, d;
		n = num;
		sum = 0;
		while(n>0) {
			d = n %10;
			sum += (d*d*d);
			n /= 10;
		}
		if(sum == num) return true;
		else return false;
	}
}
public class Armstrong {
	public static void main(String[] args) {
		DigitsOpr dig = new DigitsOpr();
		int n;
		Scanner sc = new Scanner(System.in);
		System.out.print("정수를 입력하세요: ");
		n = sc.nextInt();
		dig.setNum(n);
		if(dig.isArmstrong()) {
			System.out.println(n  + "은(는)Armstrong 수입니다.");
		}
		else {
			System.out.println(n  + "은(는)Armstrong 수가 아닙니다.");
		}
		
	}
}
반응형

'JAVA > 문법' 카테고리의 다른 글

[JAVA] 인터페이스 구현  (0) 2020.01.04
[JAVA] 추상클래스  (0) 2020.01.04
[JAVA] 배열 2  (0) 2019.12.15
[JAVA] 배열  (0) 2019.12.15
[JAVA] loop  (0) 2019.12.08
반응형

7. toString

Arrays.toString(values)

정수형 배열을 문자열로 변환하는 함수 

적용 

 

import java.util.Arrays;
import java.util.Scanner;
public class Hello{
public static void main(String[] args) {
	int[] n = {1,2,3,4,5};
	String get_values = Arrays.toString(n);
	System.out.println("values = "+ get_values);
	}
}

 

 

values = [1, 2, 3, 4, 5]

 

반응형

'JAVA > 문법' 카테고리의 다른 글

[JAVA] 추상클래스  (0) 2020.01.04
[JAVA] 클래스  (0) 2019.12.22
[JAVA] 배열  (0) 2019.12.15
[JAVA] loop  (0) 2019.12.08
[JAVA] random(랜덤) 함수  (0) 2019.12.08
반응형

1. 자바 배열 선언하기 

자료형[] 배열이름 = new 자료형[배열의 크기];

int array[];
int[] array;

위에 와 같이 선언은 되지만 

int array[5];

크기 지정이 안되기 때문에 위에와 같이 선언하면 오류가 발생함.

그렇기 때문에 

public class Hello{
public static void main(String[] args) {
	int[] array_v1 = new int[5];
	array_v1[0] = 20; 
	array_v1[1] = 40;
	array_v1[2] = 60;
	array_v1[3] = 80;
	array_v1[4] = 100;
	
	int[] array_v2 = {10, 30, 60, 90, 120};
	int[] array_v3 = new int[] {5, 10, 15, 20, 25};
	int[] array_v4;
	array_v4 = new int[5];
	array_v4[0] = 20; 
	array_v4[1] = 40;
	array_v4[2] = 60;
	array_v4[3] = 80;
	array_v4[4] = 100;
	}
}

이렇게 선언할 수 있다.

 

2. 배열 정렬

전 c언어에서는 정렬을 하기 위해서는 보통 2중 for문을 사용하곤 했다. 하지만 자바에서는 Arrays.sort(배열이름)이라는 이 한 문장으로 오름차순 배열을 할 수 있다. 

 

적용 

import java.util.Arrays;
import java.util.Scanner;
public class Hello{
public static void main(String[] args) {
	Scanner scanner = new Scanner(System.in);
	int array[] = new int[5];
	System.out.println("양수 5개를 입력하세요.");
	
	for(int i=0; i<5; i++) 
		array[i] = scanner.nextInt();
	
	Arrays.sort(array);
	System.out.println("가장 큰 수는 " + array[4] + "입니다.");
	scanner.close();
	}
}

결과 

양수 5개를 입력하세요.
30 20 24 56 18
가장 큰 수는 56입니다.

3. 다차원 배열 

자바에서 다차원 배열은 c에서의 다차원 배열과 매우 비슷한 모습을 볼 수 있다.

다만, 다른 점이 하나 있다면 배열을 선언하는 부분이다.

적용 

import java.util.Arrays;
import java.util.Scanner;
public class Hello{
public static void main(String[] args) {
	int[][] array = new int[3][4]; //2차원 배열선언 
	int i, k;
	int val = 1;
	for(i=0; i<3; i++) {
		for(k=0; k<4; k++) {
			array[i][k] = val;
			val ++;
		}
	}
	System.out.println("array[0][0]부터 array[2][3]까지 출력");
	for(i=0; i<3; i++) {
		for(k=0; k<4; k++) {
			System.out.printf("%3d", array[i][k]);
		}
		System.out.println("\n");
	}
}
}

결과

array[0][0]부터 array[2][3]까지 출력
  1  2  3  4

  5  6  7  8

  9 10 11 12

4. System.arraycopy()

System.arraycopy(src, srcPos, dest, destPos, length);

src : 복사하고자 하는 소스, 원본
srcPos :위의 소스에서 어느 부분부터 읽어올지 위치를 정함.
dest : 복사하려는 대상
destPos : 위에 dest에서 자료를 받을 때, 어느 부분부터 쓸지 시작위치를 정함.
length : 원본에서 복사본까지 얼마큼 읽어 올지 입력

 

적용

import java.util.Arrays;
import java.util.Scanner;
public class Hello{
public static void main(String[] args) {
	int[] array = {10,30,50,70,90,60};
	int[] array2 = new int[4];
	System.arraycopy(array, 2, array2, 1, 3);
	for(int i=0; i<array2.length; i++) {
		System.out.println("array["+i+"] = " + array2[i]);
		}
	}
}

결과

array[0] = 0
array[1] = 50
array[2] = 70
array[3] = 90

5. Arrays.copyof()

Arrays.copyof(Object dest, int length)

Object dest : 복사하려는 대상 
int length :  dest에서 시작해서 몇 개의 길이 만큼 복사할지 길이를 정함.

 

적용

import java.util.Arrays;
import java.util.Scanner;
public class Hello{
public static void main(String[] args) {
	int[] array = {10,30,50,70,90,60};
	int[] array2 = Arrays.copyOf(array,3);
	for(int i=0; i<array2.length; i++) {
		System.out.println("array["+i+"] = " + array2[i]);
		}
	}
}

 

결과

array[0] = 10
array[1] = 30
array[2] = 50

6. for - each

배열이나 나열의 언소를 순차 접근하는데 유용한 for 문

for(변수 : 배열 레퍼런스){
	for문 내용
}

for - each 문으로 정수 배열의 합을 구하는 예시 

int [] n = {1,2,3,4,5};
int sum = 0;
for(int k : n) {
	sum += k;
}

적용 

import java.util.Arrays;
import java.util.Scanner;
public class Hello{
public static void main(String[] args) {
	int[] n = {1,2,3,4,5};
	int sum =0;
	for(int k : n) {
		System.out.print(k + " ");
		sum  += k;
	}
	System.out.println("합은 "  + sum);
	String f[] = {"사과 ", "배", "바나나", "체리", "딸기", "포도"};
	for(String s: f) {
		System.out.print(s + " ");
		}
	}
}

결과 

1 2 3 4 5 합은 15
사과  배 바나나 체리 딸기 포도 

 

 

 

반응형

'JAVA > 문법' 카테고리의 다른 글

[JAVA] 클래스  (0) 2019.12.22
[JAVA] 배열 2  (0) 2019.12.15
[JAVA] loop  (0) 2019.12.08
[JAVA] random(랜덤) 함수  (0) 2019.12.08
[JAVA] Exception in thread "main" java.lang.ArithmeticException: 자바 예외처리  (0) 2019.12.07
반응형

짝수만 출력 

package chap03;
public class plus {

	public static void main(String[] args) {
		int i, N=20;
		for(i=2; i<=N; i+=2) {
			System.out.println(i);
		}
	}
}

홀수의 합 

1. 작은수 

package chap03;
public class plus {

	public static void main(String[] args) {
		int i, N=10, sum=0;
		for(i=1; i<=N; i++) {
			if(i%2 != 0) {
				sum  = sum + i;
			}
		}
		System.out.println(sum);
	}
}

큰수 

package chap03;
import java.util.Scanner;
public class plus {
	public static void main(String[] args) {
		Scanner s = new Scanner(System.in);
		int i, N=100, temp=0;
		System.out.print("숫자를 입력하세요: ");
		temp = s.nextInt();
		if(temp == 0 || temp==1) {
			for(i=temp; i<=N; i+=2) {
				System.out.print(i + " ");
			}
		}else {
			System.out.print("잘못 눌렀군요.");
		}
	}
}

100까지 0을 누르면 짝수, 1를 누르면 홀수가 나옴.

package chap03;
public class plus {

	public static void main(String[] args) {
		int i, N=1000, sum=0;
		for(i=500; i<=N; i++) {
			if(i%2 != 0) {
				sum  = sum + i;
			}
		}
		System.out.println(sum);
	}
}

구구단

package chap03;
import java.util.Scanner;
public class plus {
	public static void main(String[] args) {
		Scanner s = new Scanner(System.in);
		System.out.print("몇단 : ");
		int temp = s.nextInt();
		int i,j;
		for(j=1; j<=9; j++) {
			System.out.println(temp + " x " + j + " = " + temp*j);
		}
		
	}
}

합 계산

package chap03;
import java.util.Scanner;
public class plus {
	public static void main(String[] args) {
		Scanner s = new Scanner(System.in);
		System.out.print("정수를 입력하세요(양수): ");
		int temp = s.nextInt();
		System.out.println("입력한 정수는 " + temp + "입니다.");
		int i, sum=0;
		for(i=1; i<=temp; i++) {
			System.out.print(i + " ");
			sum = sum + i;
		}
		System.out.printf("\n1부터  %d까지의 합은 %d 입니다.", temp, sum);
	}
}

합계와 평균구하기 

package chap03;
import java.util.Scanner;
public class plus {
	public static void main(String[] args) {
		Scanner s = new Scanner(System.in);
		int i,n, sum=0;
		System.out.print("숫자를 입력하세요: ");
		for(i=0; i<5; i++) {
			n = s.nextInt();
			sum = sum + n;
		}
		float temp  = sum/5; 
		System.out.printf("합은 %d 평균은 %.11f입니다.", sum, temp);
	}
}

입력된 숫자까지 세제곱

package chap03;
import java.util.Scanner;
public class plus {
	public static void main(String[] args) {
		Scanner s = new Scanner(System.in);
		int i,n, sum=0;
		System.out.print("정수를 입력하세요: ");
		n = s.nextInt();
		for(i=1; i<=n; i++) {
			System.out.printf("%d의 세제곱은 %d입니다.\n", i, (i*i*i));
		}
	
	}
}

문자 거꾸로 뒤집기 

package chap03;
import java.util.Scanner;
public class plus {
	public static void main(String[] args) {
		Scanner s = new Scanner(System.in);
		System.out.print("문자열 입력 : ");
		String temp = s.nextLine();
		for(int i = temp.length()-1; i>=0; i--) {
			System.out.print(temp.charAt(i));
		}
		
	}
}

공백을 입력하고 싶으면 nextLine()

 

문장에 대문자, 소문자, 숫자 구별

package chap03;
import java.util.Scanner;
public class plus {
	public static void main(String[] args) {
		Scanner s = new Scanner(System.in);
		System.out.print("문자열 입력 : ");
		String temp = s.nextLine();
		int num1 = 0, num2 =0, num3 = 0;
		for(int i=0; i < temp.length(); i++) {
			char cnt = temp.charAt(i);
			if(cnt>='A' && cnt<= 'Z') {
				num1 ++;
			}
			if(cnt >='a' && cnt <= 'z') {
				num2 ++;
			}
			if(cnt >= '0' && cnt <= '9'){
				num3++;
			}
		}
		System.out.printf("%s : 대문자 %d개, 소문자 %d개, 숫자 %d개", temp, num1, num2, num3);
	}
}

 

반응형

'JAVA > 문법' 카테고리의 다른 글

[JAVA] 클래스  (0) 2019.12.22
[JAVA] 배열 2  (0) 2019.12.15
[JAVA] 배열  (0) 2019.12.15
[JAVA] random(랜덤) 함수  (0) 2019.12.08
[JAVA] Exception in thread "main" java.lang.ArithmeticException: 자바 예외처리  (0) 2019.12.07
반응형

Random 함수를 사용하는 방법을 알아보도록 하겠다.

 

호출 Random 객체 생성하기

import java.util.Random;
Random random = new Random();

정수 Random(int)생성 과 범위지정

int randomInt = random.nextInt();
System.out.println(randomInt)

위에 random.nextInt()안에 특정숫자를 넣으면 0부터 특정숫자-1까지 범위가 정해지고 그 안에서 랜덤 숫자가 나오게 되는 것이다. 

 

예를 들어

Random rand = new Random();
rand.nextInt(10)

이렇게 10이라는 숫자를 넣게 되면 0부터 10-1 즉, 0부터 9까지의 숫자중에 어떤 수를 구하게 되는 것이다.

package chap03;
import java.util.Random;

public class plus {

	public static void main(String[] args) {
		Random rand = new Random();
		int i, N=5;
		for(i=1; i<=N; i++) {
			System.out.printf("%d ", rand.nextInt(10+1));
		}
	}
}

이렇게 for문을 같이 사용하면 랜덤한 숫자 5개를 구할 수 있게 되는 것이다.

반응형

'JAVA > 문법' 카테고리의 다른 글

[JAVA] 클래스  (0) 2019.12.22
[JAVA] 배열 2  (0) 2019.12.15
[JAVA] 배열  (0) 2019.12.15
[JAVA] loop  (0) 2019.12.08
[JAVA] Exception in thread "main" java.lang.ArithmeticException: 자바 예외처리  (0) 2019.12.07
반응형
package chap03;
import java.util.Scanner; // 입력 

public class plus {

	public static void main(String[] args) {
		Scanner s = new Scanner(System.in);
		int a, b;
		
		while(true) {
		System.out.printf("분자를 정수로 입력하세요 : ");
		a = s.nextInt();
		System.out.printf("분모를 정수로 입력하세요 : ");
		b = s.nextInt();
       		System.out.printf("결과는  %d 입니다.\n", a/b);
		if(b == 0) {
			System.out.printf("0으로 나눌 수는 없습니다.\n");
		} 	 
	}
}

자바로 프로그래밍 하던 중  Exception in thread "main" java.lang.ArithmeticException: 이라는 오류가 발생했다. 이유를 찾아보니 '특정식을 0으로 나누었을때 발생하는 예외' 라는 것을 알게 되었다. 그래서 여러 방법을 시도해보다가 

package chap03;
import java.util.Scanner; // 입력 

public class plus {

	public static void main(String[] args) {
		Scanner s = new Scanner(System.in);
		int a, b;
		
		while(true) {
		System.out.printf("분자를 정수로 입력하세요 : ");
		a = s.nextInt();
		System.out.printf("분모를 정수로 입력하세요 : ");
		b = s.nextInt();
		if(b == 0) {
			System.out.printf("0으로 나눌 수는 없습니다.\n");
		}
		else {
			System.out.printf("결과는  %d 입니다.\n", a/b);
            System.out.println("결과는 " + a/b + " 입니다. ");
			}
		} 	 
	}
}

 이렇게 if - case문을 사용하여 예외처리를 해주면 오류없이 코드가 진행되는 것을 알 수 있다. b가 0이 되어 a를 0으로 나누어 Exception in thread "main" java.lang.ArithmeticException: 오류가 발생하면 0으로 나눌수는 없습니다를 출력하고 이것이 아니라면 두 a와 b를 나눈 값을 출력하도록 코드를 짰다.

반응형

'JAVA > 문법' 카테고리의 다른 글

[JAVA] 클래스  (0) 2019.12.22
[JAVA] 배열 2  (0) 2019.12.15
[JAVA] 배열  (0) 2019.12.15
[JAVA] loop  (0) 2019.12.08
[JAVA] random(랜덤) 함수  (0) 2019.12.08

+ Recent posts