예제 7-1

public class CaptionTvTest {
	public static void main(String[] args) {
		CaptionTv ctv = new CaptionTv();
		ctv.power();
		ctv.channel = 10;
		ctv.channelUp();
		System.out.println(ctv.channel);
		ctv.display("Hello World");
		ctv.caption = true;
		ctv.display("Hello World2");
	}

}

class Tv {
	boolean power;
	int channel;
	
	void power() {power = !power;}
	void channelUp() {channel++;}
	void channelDown() {channel--;}
}
class CaptionTv extends Tv {
	boolean caption;
	void display(String text) {
		if(caption) {
			System.out.println(text);
		}
	}
}
11
Hello World2

 

 

 

예제 7-2

public class DrawShape {
	public static void main(String[] args) {
		Point[] p = {	
				new Point(100, 100),
				new Point(140, 50),
				new Point(200, 100)
		};
		Triangle t = new Triangle(p);
		Circle c = new Circle(new Point(150, 150), 50);
		
		t.draw();
		c.draw();
	}

}

class Shape {
	String color = "black";
	void draw() {
		System.out.printf("[color=%s]%n", color);
	}
}

class Point {
	int x;
	int y;

	Point(int x, int y) {
		this.x = x;
		this.y = y;
	}

	Point() {
		this(0, 0);
	}

	String getXY() {
		return "(" + x + "," + y + ")"; // x와 y의 값을 문자열로 반환
	}
}

class Circle extends Shape {
	Point center;
	int r;

	Circle() {
		this(new Point(0, 0), 100);
}
	Circle(Point center, int r) {
		this.center = center;
		this.r = r;
	}
	
	void draw() {
		System.out.printf("[center=(%d, %d), r=%d, color=%s]%n", center.x, center.y, r, color);
	}
}

class Triangle extends Shape {
	Point[] p = new Point[3];
	
	Triangle(Point[] p) {
		this.p = p;
	}
	
	void draw() {
		System.out.printf("[p1=%s, p2=%s, p3=%s, color=%s]%n",
				p[0].getXY(),p[1].getXY(), p[2].getXY(), color);
	}
}
[p1=(100,100), p2=(140,50), p3=(200,100), color=black]
[center=(150, 150), r=50, color=black]

 

 

예제 7-3

public class DeckTest {
	public static void main(String[] args) {
		Deck d = new Deck();
		Card c = d.pick();
		System.out.println(c);

		d.shuffle();
		c = d.pick(0);
		System.out.println(c);

	}
}

class Deck {
	final int CARD_NUM = 52;
	Card cardArr[] = new Card[CARD_NUM];

	Deck() {
		int i = 0;
		for (int k = Card.KIND_MAX; k > 0; k--) {	// 4
			for (int n = 0; n < Card.NUM_MAX; n++) {	//13
				cardArr[i++] = new Card(k, n + 1);
			}
		}
		
		for(i =0 ; i < CARD_NUM ; i++) {
			cardArr[i++] = new Card(Card.KIND_MAX-i/Card.NUM_MAX, i%Card.NUM_MAX+1);
		}
	}
		// cardArr[10] ?? 무늬, 숫자
		// diamond J 23
		// heart J 36
		//Clover J 49 50 51

	Card pick(int index) {
		return cardArr[index];
	}

	Card pick() {
		return pick((int) (Math.random() * CARD_NUM));
	}

	void shuffle() {
		for (int i = 0; i < cardArr.length; i++) {
			int r = (int) (Math.random() * CARD_NUM);

			Card temp = cardArr[i];
			cardArr[i] = cardArr[r];
			cardArr[r] = temp;

		}
	}
}

class Card {
	static final int KIND_MAX = 4;
	static final int NUM_MAX = 13;

	static final int SPADE = 4;
	static final int DIAMOND = 3;
	static final int HEART = 2;
	static final int CLOVER = 1;

	int kind;
	int number;

	Card() {
		this(SPADE, 1);
	}

	Card(int kind, int number) {
		this.kind = kind;
		this.number = number;
	}

	public String toString() {
		String[] kinds = { "", "CLOVER", "HEART", "DIAMOND", "SPADE" };
		String numbers = "0123456789XJQK"; // 숫자 10은 X로 표현
		return "kind : " + kinds[this.kind] + ", number : " + numbers.charAt(this.number);
	} // toString()의 끝
} // Card클래스의 끝
kind : DIAMOND, number : 5
kind : SPADE, number : Q

 

 

 

예제 7-4

class Tv {
	boolean power;
	int channel;
	
	void power()	{ power = !power; }
	void channelUP() { ++channel; }
	void channelDown() { --channel; }
}

class VCR {
	boolean power;
	int counter = 0;
	void power() {	power = !power; }
		void play() { }
		void stop() { }
		void rew() { }
		void ff() { }
	}

class TVCR extends Tv {
	VCR vcr = new VCR();
	
	void play() {
		vcr.play();
	}
	
	void stop() {
		vcr.stop();
	}
	void rew() {
		vcr.rew();
	}
	void ff() {
		vcr.ff();
	}

}

 

 

 

 

예제 7-5

public class SuperTest {
	public static void main(String[] args) {
		Child c = new Child();
		c.method();
	}
}

class Parent {
	int x=10;
}

class Child extends Parent {
	void method() {
		System.out.println("x=" + x);
		System.out.println("this.x=" + this.x);
		System.out.println("super.x="+ super.x);
	}
}
x=10
this.x=10
super.x=10

 

 

 

 

예제 7-6

public class SuperTest2 {
	public static void main(String[] args) {
		Child c = new Child();
		c.method();
	}
}

class Parent {
	int x=10;
}

class Child extends Parent {
	int x=20;
	void method() {
		System.out.println("x=" + x);
		System.out.println("this.x=" + this.x);
		System.out.println("super.x="+ super.x);
	}
}
x=20
this.x=20
super.x=10

 

 

 

예제 7-7

public class PointTest {
	public static void main(String[] args) {
		Point3D p3 = new Point3D(1,2,3);
	}
}

class Point {
	int x, y;
	
	Point(int x, int y) {
		this.x = x;
		this.y = y;
	}
	
	String getLocation() {
		return "x :" + x + ", y :"+ y;
	}
}

class Point3D extends Point {
	int z;
	
	Point3D(int x, int y, int z) {
		
		this.x = x;
		this.y = y;
		this.z = z;
	}
	
	String getLocation() {
		return "x :" + x + ", y :" + y + ", z :" + z;
	}
}

 

 

 

예제 7-8

class PointTest2 {
	public static void main(String[] args) {
		Point3D p3 = new Point3D();
		System.out.println("p3.x="+ p3.x);
		System.out.println("p3.y="+ p3.y);
		System.out.println("p3.z="+ p3.z);

	}

}

class Point {
	int x = 10;
	int y = 20;

	Point(int x, int y) {

		this.x = x;
		this.y = y;
	}
}

class Point3D extends Point {
	int z = 30;

	Point3D() {
		this(100, 200, 300);
	}

	Point3D(int x, int y, int z) {
		super(x, y);
		this.z = z;
	}
}
p3.x=100
p3.y=200
p3.z=300

 

 

 

예제 7-9

package com.codechobo.book;

public class PackageTest {
	public static void main(String[] args) {
		System.out.println("Hello World!");
	}
}

 

 

 

예제 7-10

import java.text.SimpleDateFormat;
import java.util.Date;

public class ImportTest {
	public static void main(String[] args) {
		Date today = new Date();
		
		SimpleDateFormat date = new SimpleDateFormat("yyyy/mm/dd");
		SimpleDateFormat time = new SimpleDateFormat("hh:mm:ss a");
		
		System.out.println("오늘 날짜는 " + date.format(today));
		System.out.println("현재 시간은 " + time.format(today));
	}
}

 

 

 

예제 7-11

import static java.lang.System.out;
import static java.lang.Math.*;

public class StaticImportEx1 {
	public static void main(String[] args) {
//		System.out.println(Math.random());
		out.println(random());
		
//		System.out.println("Math.PI :"+Math.PI);
		out.println("Math.PI :" + PI);
	}
}
0.25032972960374855
Math.PI :3.141592653589793

 

 

 

예제 7-12 

class Card {
	final int NUMBER;
	final String KIND;
	static int width = 100;
	static int height = 250;

	Card(String kind, int num) {
		KIND = kind;
		NUMBER = num;

	}

	Card() {
		this("HEART", 1);
	}

	public String toString() {
		return KIND + " " + NUMBER;
	}
}

class FinalCardTest {
	public static void main(String[] args) {
		Card c = new Card("HEART", 10);
//	c.NUMBER = 5;
		System.out.println(c.KIND);
		System.out.println(c.NUMBER);
		System.out.println(c);
	}
}
HEART
10
HEART 10

 

 

 

예제 7-13

public class TimeTest {
	public static void main(String[] args) {
		Time t = new Time(12, 35, 30);
		System.out.println(t);
//		t.hour = 13;
		t.setHour(t.getHour() + 1); // 13을들고오고싶으면 getHour 바꾸고싶으면 setHour
		System.out.println(t);
	}
}

// VO, Component
class Time {
	private int hour, minute, second;
	boolean power;

	public Time(int hour, int minute, int second) {
		super();
		this.hour = hour;
		this.minute = minute;
		this.second = second;
	}
	public boolean isPower() {
		return power;
	}
	public void setPower(boolean power) {
		this.power = power;
	}
	public int getHour() {	return hour; }
	public void setHour(int hour) {
		
		if(hour < 0 || hour > 23) return;
		this.hour = hour;
	}
	
	public int getMinute() {	return minute; }
	public void setMinute(int minute) {
		
		if(minute < 0 || minute > 59) return;
		this.minute = minute;
	}
	public int getSecond() {	return second;}
	public void setSecond(int second) {
		if (second < 0 || second > 59) return;
		this.second = second;
	}
	public String toString() {
		return hour + ":" + minute + ":" + second;
	}

}
12:35:30
13:35:30

 

 

 

 

예제 7-14

public class CastingTest1_1 {
	public static void main(String[] args) {
		Car car = null;
		FireEngine fe = new FireEngine();
		FireEngine fe2 = null;

		fe.water();
		car = (Car)fe;	//Car타입의 참조형변수라고 명시하지 않아도 된다.
//		car.water();
		fe2 = (FireEngine) car;
		fe2.water();
	}
}

class Car {
	String color;
	int door;

	void drive() {
		System.out.println("drive, brrrr~");
	}

	void stop() {
		System.out.println("stop!!!");
	}
}

class FireEngine extends Car {
	void water() {
		System.out.println("water!!!");
	}
}
water!!!
water!!!

 

 

 

 

예제 7-15

class CastingTest2 {
	public static void main(String[] args) {
		Car car = new Car();
		Car car2 = null;
		FireEngine fe = null;
		
		car.drive();
		fe = (FireEngine)car;
		fe.drive();
		car2 = fe;
		car2.drive();
	}
}
fe = (FireEngine)car; // 에러발생

 

 

 

 

예제 7-16

class CastingTest2 {
	public static void main(String[] args) {
		Car car = new Car();
		Car car2 = null;
		FireEngine fe = null;
		
		car.drive();
		fe = (FireEngine)car;
		fe.drive();
		car2 = fe;
		car2.drive();
	}
}
drive, brrrr~Exception in thread "main" java.lang.ClassCastException: a210719.Car cannot be cast to a210719.FireEngine

	at a210719.CastingTest2.main(CastingTest2.java:10)

 

 

 

예제 7-17

public class InstanceofTest {
	public static void main(String[] args) {
		FireEngine fe = new FireEngine();
		Car car = fe;
		Object obj = fe;

		FireEngine fe2 = (FireEngine)obj;
		if (fe instanceof FireEngine) {
			System.out.println("This is a FireEngine instance.");
		}
		if (fe instanceof Car) {
			System.out.println("This is a Car instance.");
		}
		if (fe instanceof Object) {
			System.out.println("This is a Object instance.");
		}
		System.out.println(fe.getClass().getName());
		System.out.println(fe.getClass().getSimpleName());
	}
}
This is a FireEngine instance.
This is a Car instance.
This is a Object instance.
a210719.FireEngine
FireEngine

 

 

 

 

예제 7-18

public class BindingTest {
	public static void main(String[] args) {
		Parent p = new Child();
		Child c = new Child();
		
		System.out.println("p.x = " + p.x);
		p.method();
		
		System.out.println("c.x = " + c.x);
		c.method();
	}

}

class Parent {
	int x = 100;
	
	void method() {
		System.out.println("Parent Method");
	}
}

class Child extends Parent {
	int x = 200;
	
	void method() {
		System.out.println("Child Method");
	}
}
p.x = 100
Child Method
c.x = 200
Child Method

 

 

 

예제 7-19

public class BindingTest2 {
	public static void main(String[] args) {
		Parent p = new Child();
		Child c = new Child();

		System.out.println("p.x = " + p.x);
		p.method();

		System.out.println("c.x = " + c.x);
		c.method();
	}

}

class Parent {
	int x = 100;

	void method() {
		System.out.println("Parent Method");
	}
}
class Child extends Parent {
}
p.x = 100
Parent Method
c.x = 100
Parent Method

 

 

 

예제 7-20

class BindingTest3 {
	public static void main(String[] args) {
		Parent p = new Child();
		Child c = new Child();

		System.out.println("p.x = " + p.x);
		p.method();
		System.out.println();
		System.out.println("c.x = " + c.x);
		c.method();
	}
}

class Parent {
	int x = 100;

	void method() {
		System.out.println("Parent Method");
	}
}

class Child extends Parent {
	int x = 200;

	void metohd() {
		System.out.println("x=" + x);
		System.out.println("super.x=" + super.x);
		System.out.println("this.x=" + this.x);
	}
}
p.x = 100
Parent Method

c.x = 200
Parent Method

 

 

 

 

 

 

 

예제 7-21

class Product{
	int price;
	int bonusPoint;
	
	Product(int price) {
		this.price = price;
		bonusPoint = (int)(price/10.0);
	}
}
class Tv extends Product {
	Tv() {
		super(100);
	}
	public String toString() { return "Tv"; }
}
class Computer extends Product {
	Computer() { super(200); }
	
	public String toString() { return "Computer"; }
}

class Buyer {
	int money = 1000;
	int bonusPoint = 0;
	
	void buy(Product p) {
		if(money < p.price) {
			System.out.println("잔액이 부족하여 물건을 살 수 없습니다.");
			return;
		}
		
		money -= p.price;
		bonusPoint += p.bonusPoint;
		System.out.println(p + "을/를 구입하셨습니다.");
	}
}
class PolyArgumentTest {
	public static void main(String[] args) {
		Buyer b = new Buyer();
		
		b.buy(new Tv());
		b.buy(new Computer());
		
		System.out.println("현재 남은 돈은 " + b.money + "만원입니다.");
		System.out.println("현재 보너스 점수는" + b.bonusPoint + "점입니다.");
		
	}
}
Tv을/를 구입하셨습니다.
computer을/를 구입하셨습니다.
현재 남은 돈은 700만원입니다.
현재 보너스 점수는30점입니다.

 

 

 

예제 7-22

class Product {
	int price;
	int bonusPoint;

	Product(int price) {
		this.price = price;
		bonusPoint = (int) (price / 10.0);
	}

	Product() {
	}
}

class Tv extends Product {
	Tv() {
		super(100);
	}

	public String toString() {
		return "Tv";
	}
}

class Computer extends Product {
	Computer() {
		super(200);
	}

	public String toString() {
		return "Computer";
	}
}

class Audio extends Product {
	Audio() {
		super(50);
	}

	public String toString() {
		return "Audio";
	}
}

class Buyer {
	int money = 1000;
	int bonusPoint = 0;
	Product[] item = new Product[10];
	int i = 0;

	void buy(Product p) {
		if (money < p.price) {
			System.out.println("잔액이 부족하여 물건을 살 수 없습니다.");
			return;
		}

		money -= p.price;
		bonusPoint += p.bonusPoint;
		item[i++] = p;
		System.out.println(p + "을/를 구입하셨습니다.");
	}

	void summary() {
		int sum = 0;
		String itemList = "";

		for (int i = 0; i < item.length; i++) {
			if (item[i] == null)
				break;
			sum += item[i].price;
			itemList += item[i] + ", ";
		}

		System.out.println("구입하신 물품의 총금액은 " + sum + "만원입니다.");
		System.out.println("구입하신 제품은 " + itemList + "입니다.");
	}
}

class PolyArgumentTest2 {
	public static void main(String args[]) {
		Buyer b = new Buyer();

		b.buy(new Tv());
		b.buy(new Computer());
		b.buy(new Audio());
		b.summary();
	}
}
Tv을/를 구입하셨습니다.
Computer을/를 구입하셨습니다.
Audio을/를 구입하셨습니다.
구입하신 물품의 총금액은 350만원입니다.
구입하신 제품은 Tv, Computer, Audio, 입니다.

 

 

 

 

예제 7-23

import java.util.*;
	class Product {
		int price;
		int bonusPoint;
		
		Product(int price) {
			this.price = price;
			bonusPoint = (int)(price/10.0);
		}
		
		Product() {
			price = 0;
			bonusPoint = 0;
		}
	}



class Tv extends Product {
	Tv() { super(100); }
	public String toString() { return "Tv"; }
}

class Computer extends Product {
	Computer() { super(200); }
	public String toString() { return "computer";	}
}

class Audio extends Product {
	Audio() {	super(50);	}
	public String toString() {	return "Audio";	}
}

class Buyer {
	int money = 1000;
	int bonusPoint = 0;
	Vector<Product> item = new Vector<Product>();
	
	void buy(Product p) {
		if(money < p.price) {
			System.out.println("잔액이 부족하여 물건을 살 수 없습니다.");
			return;
		}
		money -= p.price;
		bonusPoint += p.bonusPoint;
		item.add(p);
		System.out.println(p + "을/를 구입하셨습니다.");
	}
	
	void refund(Product p) {
		if(item.remove(p)) {
			bonusPoint -= p.bonusPoint;
			System.out.println(p + "을/를 반품하셨습니다.");
		} else { System.out.println("구입하신 제품 중 해당 제품이 없습니다.");
	}
}
	
void summary() {
	int sum = 0;
	String itemList ="";
	
	if(item.isEmpty()) {
		System.out.println("구입하신 제품이 없습니다.");
		return;
	}
	
	for(int i = 0; i < item.size();i++) {
		Product p = (Product)item.get(i);
		sum += p.price;
		itemList += (i==0) ? "" + p : ", " + p;
	}
	System.out.println("구입하신 물품의 총금액은 " + sum + "만원입니다.");
	System.out.println("구입하신 제품은 "+ itemList + "입니다.");
}
}

public class PolyArgumentTest3 {
	public static void main(String[] args) {
		Buyer b = new Buyer();
		Tv tv = new Tv();
		Computer com = new Computer();
		Audio audio = new Audio();

		b.buy(tv);
		b.buy(com);
		b.buy(audio);
		b.summary();
		System.out.println();
		b.refund(com);
		b.summary();
	}
}

 

 

 

 

예제 7-24

public class FighterTest {
	public static void main(String[] args) {
		Fighter f = new Fighter();
		Fightable fightable = new Fighter();
				
		if(f instanceof Unit) {
			System.out.println("f는 Unit의 자손입니다");
		}
		if(f instanceof Fightable) {
			System.out.println("f는 Fightable인터페이스를 구현했습니다");
		}
		if(f instanceof Attackable) {
			System.out.println("f는 Attackable인터페이스를 구현했습니다");
		}
		if(f instanceof Movable) {
			System.out.println("f는 Movable인터페이스를 구현했습니다");
		}
		if(f instanceof Object) {
			System.out.println("f는 Object클래스의 자손입니다");
		}
		
	}
}

class Fighter extends Unit implements Fightable {
	public void attack(Unit u) {
		// 내용생략
	}
	public void move(int x, int y) {
		// 내용생략
	}
}
class Unit {
	int currentHP;
	int x;
	int y;
	
}
interface Fightable extends Movable, Attackable{}
interface Movable { void move(int x, int y); }
interface Attackable { void attack(Unit u); }
f는 Unit의 자손입니다
f는 Fightable인터페이스를 구현했습니다
f는 Attackable인터페이스를 구현했습니다
f는 Movable인터페이스를 구현했습니다
f는 Object클래스의 자손입니다

 

 

 

 

예제 7-25

interface Parseable {
	public abstract void parse(String fileName);
}

class ParserManager {
	public static Parseable getParser(String type) {
		if (type.equals("XML")) {
			return new XMLParser();
		} else {
			Parseable p = new HTMLParser();
			return p;
		}

	}
}

class XMLParser implements Parseable {
	@Override
	public void parse(String fileName) {
		System.out.println(fileName + "- XML parsing completed.");
	}
}

class HTMLParser implements Parseable {
	@Override
	public void parse(String fileName) {
		System.out.println(fileName + "-HTML parsing completed.");

	}
}

class parserTest {
	public static void main(String args[]) {
		Parseable parser = ParserManager.getParser("XML");
		parser.parse("document.xmml");
		parser = ParserManager.getParser("HTML");
		parser.parse("document2.html");
	}
}

 

 

 

 

예제 7-26

public class RepairableTest {
	public static void main(String[] args) {
		Tank tank = new Tank();
		Dropship dropship = new Dropship();
		
		Marine marine = new Marine();
		SCV scv = new SCV();
		scv.repair(tank);
		scv.repair(dropship);
//		scv.repair(marine);
	}
}

interface Repairable{}

class Unit {
	int hitPoint;
	final int MAX_HP;
	Unit(int hp) {
		MAX_HP = hp;
	}
	//...
}

class GroundUnit extends Unit {
	GroundUnit(int hp) {
		super(hp);
	}
}

class AirUnit extends Unit {
	AirUnit(int hp) {
		super(hp);
	}
}


class Tank extends GroundUnit implements Repairable {
	Tank() {
		super(150);
		hitPoint = MAX_HP;
	}
	
	public String toString() {
		return "Tank";
	}
	//...
}

class Dropship extends AirUnit implements Repairable {
	Dropship() {
		super(125);
		hitPoint = MAX_HP;
	}
	
	public String toString() {
		return "Dropship";
	}
	//...
}

class Marine extends GroundUnit {
	Marine() {
		super(40);
		hitPoint = MAX_HP;
	}
	//...
}

class SCV extends GroundUnit implements Repairable{
	SCV() {
		super(60);
		hitPoint = MAX_HP;
	}
	
	void repair(Repairable r) {
		if (r instanceof Unit) {
			Unit u = (Unit)r;
			while(u.hitPoint!=u.MAX_HP) {
				u.hitPoint++;
			}
			System.out.println( u.toString() + "의 수리가 끝났습니다.");
		}
		//...
	}
}
Tank의 수리가 끝났습니다.
Dropship의 수리가 끝났습니다.

 

 

 

 

예제 7-27

import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

import javax.print.attribute.HashAttributeSet;

public class InterfaceTest {
	public static void main(String[] args) {
		// List 순번을 통해 자료관리
		// Map Key(이름)을 통해 자료관리

		Map<String, String> map = new HashMap<String, String>();
		map.put("이름", "홍길동");
		map.put("나이", "40");
		map.put("주소", "서울시 영등포구");

		System.out.println(map);
		System.out.println(map.get("이름"));
		System.out.println(map.get("나이"));
		System.out.println(map.get("주소"));

		for (Map.Entry<String, String> m : map.entrySet()) {

		}
	}
}

class A {
	public void methodA(I i) {
		i.methodB();
	}
}

class B implements I {
	public void methodB() {
		System.out.println("methodB()");
	}
}

interface I {
	default void methodB(int i) {
	}

	void methodB();

	static interface I2 {
	}
}

class C {
	private static int i;

	class D {
		class E {
			class F {
			}
		}
	}

	void m() {
	}

}

 

 

 

 

예제 7-28

class A {
	void autoPlay(I i) {
		i.play();
	}
}

interface I {
	public abstract void play();
}

class B implements I {
	public void play() {
		System.out.println("play in B class");
	}
}

class C implements I {
	public void play() {
		System.out.println("play in C class");
	}
}

class InterfaceTest2 {
	public static void main(String[] args) {
		A a = new A();
		a.autoPlay(new B());
		a.autoPlay(new C());
	}
}
play in B class
play in C class

 

 

 

 

예제 7-29

public class InterfaceTest3 {
	public static void main(String[] args) {
		A a = new A();
		a.methodA();
	}
}

class A {
	void methodA() {
		I i = InstanceManager.getInstance();
		i.methodB();
		System.out.println(i.toString());
	}
}

interface I {
	public abstract void methodB();
}

class B implements I {
	public void methodB() {
		System.out.println("methodB in B class");
	}

	public String toString() {
		return "class B";
	}
}

class InstanceManager {
	public static I getInstance() {
		return new B();
	}
}
methodB in B class
class B

 

 

 

 

예제 7-30

public class DefaultMethodTest {
	public static void main(String[] args) {
		Child c = new Child();
		c.method1();
		c.method2();
		MyInterface.staticMethod();
		MyInterface2.staticMethod();
	}
}

class Child extends Parent implements MyInterface, MyInterface2 {
	public void method1() {
		System.out.println("method1() in Child"); // 오버라이딩
	}
}

class Parent {
	public void method2() {
		System.out.println("method2() in Parent");
	}
}

interface MyInterface {
	default void method1() {
		System.out.println("method1() in MyInterface");
	}

	default void method2() {
		System.out.println("method2() in MyInterface");
	}

	static void staticMethod() {
		System.out.println("staticMethod() in MyInterface");
	}
}

interface MyInterface2 {
	default void method1() {
		System.out.println("method1() in MyInterface2");
	}

	static void staticMethod() {
		System.out.println("staticMethod() in MyInterface2");
	}
}
method1() in Child
method2() in Parent
staticMethod() in MyInterface
staticMethod() in MyInterface2

 

 

 

 

예제 7-31

class InnerEx1 {
	class InstanceInner {
		int iv = 100;
//		static int cv = 100;
		final static int CONST = 100;
	}

	static class StaticIneer {
		int iv = 200;
		static int cv = 200;
	}

	void myMethod() {
		class LocalInner {
			int iv = 300;
//			static int cv = 300;
			final static int CONST = 300;
		}
	}

	public static void main(String[] args) {
		System.out.println(InstanceInner.CONST);
		System.out.println(StaticIneer.cv);
	}
}
100
200

 

 

 

예제 7-32

class InnerEx1 {
	class InstanceInner {
		int iv = 100;
//		static int cv = 100;
		final static int CONST = 100;
	}

	static class StaticIneer {
		int iv = 200;
		static int cv = 200;
	}

	void myMethod() {
		class LocalInner {
			int iv = 300;
//			static int cv = 300;
			final static int CONST = 300;
		}
	}

	public static void main(String[] args) {
		System.out.println(InstanceInner.CONST);
		System.out.println(StaticIneer.cv);
	}
}

 

 

 

예제 7-32

class InnerEx2 {
	class InstanceInner {
	}

	static class StaticInner {
	}

	InstanceInner iv = new InstanceInner();
	static StaticInner cv = new StaticInner();

	static void staticMethod() {
//		InstanceInner obj1 = new InstanceInner();
		StaticInner obj2 = new StaticInner();

		InnerEx2 outer = new InnerEx2();
		InstanceInner obj1 = outer.new InstanceInner();
	}

	void instanceMethod() {
		InstanceInner obj1 = new InstanceInner();
		StaticInner obj2 = new StaticInner();
//		LocalInner lv = new LocalInner();
	}

	void myMethod() {
		class LocalInner {
		}
		LocalInner lv = new LocalInner();
	}
}

 

 

 

 

예제 7-33

class InnerEx3 {
	private int outerIv = 0;
	static int outerCv = 0;
	
	class InstanceInner {
		int iiv = outerIv;
		int iiv2 = outerCv;
	}
	
	static class StaticInner {
//		int siv = outerIv;
		static int scv = outerCv;
	}
	
	void myMethod() {
		int lv = 0;
		final int LV = 0;
		
		class LocalInner {
			int liv = outerIv;
			int liv2 = outerCv;
			int liv3 = lv;
			int liv4 = LV;
		}
	}

}

 

 

 

 

 

 

예제 7-34

class Outer {
	class InstanceInner {
		int iv = 100;
	}
	
	static class StaticInner{
		int iv = 200;
		static int cv = 300;
	}
	
	void myMethod() {
		class LocalInner {
			int iv = 400;
		}
	}

}

class InnerEx4 {
	public static void main(String[] args) {
		Outer oc = new Outer();
		Outer.InstanceInner ii = oc.new InstanceInner();
		
		System.out.println("ii.iv : "+ ii.iv);
		System.out.println("Outer.StaticInner.cv : "+ Outer.StaticInner.cv);
		
		Outer.StaticInner si = new Outer.StaticInner();
		System.out.println("si.iv : "+ si.iv);
	}
}

 

 

 

 

예제 7-35

class Outer {
	int value = 10;

	class Inner {
		int value = 20;

		void method1() {
			int value = 30;
			System.out.println("value :" + value);
			System.out.println("this.value :" + this.value);
			System.out.println("Outer.this.value :" + Outer.this.value);
		}
	}

}

class InnerEx5 {
	public static void main(String[] args) {
		Outer outer = new Outer();
		Outer.Inner inner = outer.new Inner();
		inner.method1();
	}
}

 

 

 

 

예제 7-36

public class InnerEx6 {
	Object iv = new Object () { void method() {} };
	static Object cv = new Object() { void method() {} };
	
	void myMethod() {
		Object lv = new Object() { void method() {} };
	}

}

 

 

 

 

예제 7-37

import java.awt.*;
import java.awt.event.*;

class InnerEx7 {
	public static void main(String[] args) {
		Button b = new Button("Start");
		b.addActionListener(new EventHandler());
	}
}
class EventHandler implements ActionListener {
	public void actionPerformed(ActionEvent e) {
		System.out.println("ActionEvent occurred!!!");
	}
}

 

 

 

 

예제 7-38

import java.awt.*;
import java.awt.event.*;

class InnerEx8 {
	public static void main(String[] args) {
		Button b = new Button("Start");
		b.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				System.out.println("ActionEvent occurred!!!");
			}
		});
	}
}

 

class Tv {
	String color;
	boolean power;
	int channel;
	void power() {power = !power;}
	void channelUp() { ++channel;}
	void channelDown() { --channel;}

}

class TvTest{
	public static void main(String[] args) {
		Tv t;
		t = new Tv(); 
		t.channel = 7;
		t.channelDown();
		System.out.println("현재 채널은 " + t.channel + " 입니다.");
	}
}
현재 채널은 6 입니다.

 

 

 

class Tv {
	String color;
	boolean power;
	int channel;
	void power() {power = !power;}
	void channelUp() { ++channel;}
	void channelDown() { --channel;}

}
public class TvTest2 {
	public static void main(String[] args) {
		Tv t1 = new Tv();
		Tv t2 = new Tv();
		System.out.println("t1의 channel값은 " + t1.channel + "입니다:");
		System.out.println("t2의 channel값은 " + t2.channel + "입니다:");
		
		t1.channel = 7;
		System.out.println("t1의 channel값을 7로 변경하였습니다.");
		
		System.out.println("t1의 channel값은 " + t1.channel + "입니다:");
		System.out.println("t2의 channel값은 " + t2.channel + "입니다:");
	}
}
		
		System.out.println("t1의 channel값은 " + t1.channel + "입니다:");
		System.out.println("t2의 channel값은 " + t2.channel + "입니다:");
	}

}
t1의 channel값은 0입니다:
t2의 channel값은 0입니다:
t1의 channel값을 7로 변경하였습니다.
t1의 channel값은 7입니다:
t2의 channel값은 0입니다:

 

 

 

class Tv {
	String color;
	boolean power;
	int channel;
	void power() {power = !power;}
	void channelUp() { ++channel;}
	void channelDown() { --channel;}

}
public class TvTest3 {
	public static void main(String[] args) {
		Tv t1 = new Tv();
		Tv t2 = new Tv();
		
		System.out.println("t1의 channel값은 " + t1.channel + "입니다");
		System.out.println("t2의 channel값은 " + t2.channel + "입니다");
		
		t2 = t1;
		t1.channel = 7;
		System.out.println("t1의 channel값을 7로 변경하였습니다.");
		
		System.out.println("t1의 channel값은 " + t1.channel + "입니다:");
		System.out.println("t2의 channel값은 " + t2.channel + "입니다:");
		
		Tv[] tvArr = new Tv[3];
		tvArr[0].channel = 10;
	}
}
t1의 channel값은 0입니다
t2의 channel값은 0입니다
t1의 channel값을 7로 변경하였습니다.
t1의 channel값은 7입니다:
t2의 channel값은 7입니다:

 

 

 

public class TvTest4 {
	public static void main(String[] args) {
		Tv[] tvArr = new Tv[3];
		
		for(int i=0; i <tvArr.length;i++) {
			tvArr[i] = new Tv();
			tvArr[i].channel = i+10;
		}
		
		for(int i=0; i<tvArr.length;i++) {
			tvArr[i].channelUp();
			System.out.printf("tvArr[%d].channel=%d%n",i,tvArr[i].channel);
		}
	}
}
class Tv {
	String color;
	boolean power;
	int channel;
	void power() {power = !power;}
	void channelUp() { ++channel;}
	void channelDown() { --channel;}

}
tvArr[0].channel=11
tvArr[1].channel=12
tvArr[2].channel=13

 

 

public class CardTest {
	public static void main(String[] args) {
		System.out.println("Card.width = " + Card.width);
		System.out.println("Card.width = " + Card.height);
		
		Card c1 = new Card();
		c1.kind = "Heart";
		c1.number = 7;
		
		Card c2 = new Card();
		c2.kind = "Spade";
		c2.number = 4;
		
		System.out.println("c1은 " + c1.kind + ", " + c1.number + "이며, 크기는 (" + c1.width + ", " + c1.height + ")");
		System.out.println("c2은 " + c2.kind + ", " + c2.number + "이며, 크기는 (" + c2.width + ", " + c2.height + ")"); //c1 c2를Card로 바꿔도 값이 같다
		System.out.println("c1의 width와 height를 각각 50, 80으로 변경합니다.");
		
		c1.width = 50;
		c1.height = 80;
		
		System.out.println("c1은 " + c1.kind + ", " + c1.number + "이며, 크기는 (" + c1.width + ", " + c1.height + ")") ;
		System.out.println("c2은 " + c2.kind + ", " + c2.number + "이며, 크기는 (" + c2.width + ", " + c2.height + ")") ;
	}
}
class Card {
	String kind;
	int number;
	static int width = 100;
	static int height = 250;
}
Card.width = 100
Card.width = 250
c1은 Heart, 7이며, 크기는 (100, 250)
c2은 Spade, 4이며, 크기는 (100, 250)
c1의 width와 height를 각각 50, 80으로 변경합니다.
c1은 Heart, 7이며, 크기는 (50, 80)
c2은 Spade, 4이며, 크기는 (50, 80)

 

 

 

public class MyMathTest {
	public static void main(String[] args) {
		MyMath mm = new MyMath();
		
		long result1 = mm.add(5L, 3L);
		long result2 = mm.subtract(5L, 3L);
		long result3 = mm.multiply(5L, 3L);
		double result4 = mm.divide(5L, 3L);
		
		System.out.println("add(5L, 3L) = " + result1);
		System.out.println("subtract(5L, 3L) = " + result2);
		System.out.println("multiply(5L, 3L) = " + result3);
		System.out.println("divide(5L, 3L) = " + result4);
	}
}

class MyMath {long add(long a, long b) {
	long result = a+b;
	return result;
	}
	long subtract(long a, long b) {return a -b;}
	long multiply(long a, long b) { return a * b;}
	double divide(double a, double b) {return a / b;}
}
add(5L, 3L) = 8
subtract(5L, 3L) = 2
multiply(5L, 3L) = 15
divide(5L, 3L) = 1.6666666666666667

 

 

 

public class CallStackTest {
	public static void main(String[] args) {
		firstMethod();
	}
	static void firstMethod() {
		secondMethod();
	}
	static void secondMethod() {
		System.out.println("secondMethod()");
	}
}
secondMethod()

 

 

public class CallStackTest2 {
	public static void main(String[] args) {
		System.out.println("main(String[] args)이 시작되었음.");
		firstMethod();
		System.out.println();
	}
	static void firstMethod() {
		System.out.println("firstMethod()이 시작되었음.");
		secondMethod();
		System.out.println("firstMethod()이 끝났음.");
	}
	static void secondMethod() {
		System.out.println("secondMethod()이 시작되었음.");
		System.out.println("secondMethod()이 끝났음.");
	}
}
main(String[] args)이 시작되었음.
firstMethod()이 시작되었음.
secondMethod()이 시작되었음.
secondMethod()이 끝났음.
firstMethod()이 끝났음.

 

 

public class PrimitiveParamEx {
	public static void main(String[] args) {
		Data d = new Data();
		d.x = 10;
		System.out.println("main() : x = " + d.x);
		
		change(d.x);
		System.out.println("After change(d.x)");
		System.out.println("main() : x = " + d.x);
		
	}
	static void change(int x) {
		x = 1000;
		System.out.println("change1() : x = " + x);
	}
}
main() : x = 10
change1() : x = 1000
After change(d.x)
main() : x = 10

 

 

 

public class ReferenceParamEx {
	public static void main(String[] args) {
		Data d = new Data();
		d.x = 10;
		System.out.println("main() : x = " + d.x);

	}

	static void change(Data d) {
		d.x = 1000;
		System.out.println("change() : x = " + d.x);

	}
}
main() : x = 10

 

public class ReferenceParamEx2 {
	public static void main(String[] args) {
		int[] x = {10};
		System.out.println("main() : x = "+ x[0]);
		
		change(x);
		System.out.println("After change(x)");
		System.out.println("main() : x = "+ x[0]);
	}
	
	static void change(int[] x) {
		x[0] = 1000;
		System.out.println("change() : x = " +x[0]);
	}
}
main() : x = 10
change() : x = 1000
After change(x)
main() : x = 1000

 

 

 

public class ReturnTest {
	public static void main(String[] args) {
		ReturnTest r = new ReturnTest();

		int result = r.add(3, 5);
		System.out.println(result);

		int[] result2 = { 0 };
		r.add(3, 5, result2);
		System.out.println(result2[0]);
	}

	int add(int a, int b) {
		return a + b;
	}

	void add(int a, int b, int[] result) {
		result[0] = a + b;
	}
}

 

 

 

 

class Date {int x;}

public class ReferenceReturnEx_1 {
	public static void main(String[] args) {
		Date d = new Date();
		d.x = 10;
		
		Date d2 = copy(d);
		
		System.out.println("d.x ="+d.x);
		System.out.println("d2.x="+d2.x);
	}

	static Date copy(Date Date) {
		Date tmp = new Date();
		tmp.x = Date.x;
		
		return tmp;
	}
}
d.x =10
d2.x=10

 

 

 

public class FactorialTest {
	public static void main(String[] args) {
		int result = factorial(4);
		
		System.out.println(result);
		
	}
	
	static int factorial(int n) {
		int result=0;
		if(n==1)
			result = 1;
		else
			result = n * factorial(n-1);
		
		return result;
	}
}
24

 

 

 

public class FactorialTest2 {
	static long factorial(int n) {
		if(n<=0 || n>20) return -1;
		if(n<=1) return 1;
		return n * factorial(n-1);
	}
	
	public static void main(String[] args) {
		int n =21;
		long result = 0;
		
		for(int i = 1; i <= n; i++) {
			result = factorial(i);
			
			if(result==-1) {
				System.out.printf("유효하지 않은 값입니다.(0<n<=20):%d%n", n);
				break;
			}
			
			System.out.printf("%2d!=%20d%n", i, result);
		}
	}
}
 1!=                   1
 2!=                   2
 3!=                   6
 4!=                  24
 5!=                 120
 6!=                 720
 7!=                5040
 8!=               40320
 9!=              362880
10!=             3628800
11!=            39916800
12!=           479001600
13!=          6227020800
14!=         87178291200
15!=       1307674368000
16!=      20922789888000
17!=     355687428096000
18!=    6402373705728000
19!=  121645100408832000
20!= 2432902008176640000
유효하지 않은 값입니다.(0<n<=20):21

 

 

 

public class MainTest {
	public static void main(String[] args) {
		main(null);
	}
}
Exception in thread "main" java.lang.StackOverflowError
	at a210715.MainTest.main(MainTest.java:5)
	at a210715.MainTest.main(MainTest.java:5)
    ...
	at a210715.MainTest.main(MainTest.java:5)
	at a210715.MainTest.main(MainTest.java:5)
	at a210715.MainTest.main(MainTest.java:5)

 

 

 

public class PowerTest {
	public static void main(String[] args) {
		int x = 2;
		int n = 5;
		long result = 0;
		
		for(int i=1; i<=n; i++) {
			result += power(x, i);
		}
		System.out.println(result);
	}
	
	static long power (int x, int n) {
		if(n==1) return x;
		return x * power(x, n-1);
	}
}
62

 

 

 

class MyMath2 {
	long a, b;
	
	long add()		{ return a + b;	}
	long subtract()	{ return a - b;	}
	long multiply()	{ return a * b;	}
	double divide()	{ return a / b;	}
	
	static long		add(long a, long b)			{ return a + b;	}
	static long		subtract(long a, long b)	{ return a - b;	}
	static long		multiply(long a, long b)	{ return a * b;	}
	static double	divide(double a, double b)	{ return a / b;	}
}

class MyMathTest2 {
	public static void main(String[] args) {
		System.out.println(MyMath2.add(200L, 100L));
		System.out.println(MyMath2.subtract(200L, 100L));
		System.out.println(MyMath2.multiply(200L, 100L));
		System.out.println(MyMath2.divide(200.0, 100.0));
		
		MyMath2 mm = new MyMath2();
		mm.a = 200L;
		mm.b = 100L;
		
		System.out.println(mm.add());
		System.out.println(mm.subtract());
		System.out.println(mm.multiply());
		System.out.println(mm.divide());
	}
}
300
100
20000
2.0
300
100
20000
2.0

 

 

 

public class OverloadingTest {
	public static void main(String[] args) {
		MyMath3 mm = new MyMath3();
		System.out.println("mm.add(3, 3) 결과:" + mm.add(3,3));
		System.out.println("mm.add(3L, 3) 결과: " + mm.add(3L,3));
		System.out.println("mm.add(3, 3L) 결과: " + mm.add(3,3L));
		System.out.println("mm.add(3L, 3L) 결과: " + mm.add(3L,3L));
		
		int[] a = {100, 200, 300};
		System.out.println("mm.add(a) 결과: " + mm.add(a));
	}

}

class MyMath3 {
	int add(int a, int b) {
		System.out.print("int add(int a, int b) -");
		return a+b;
	}
	
	long add(int a, long b) {
		System.out.print("long add(int a, long b) - ");
		return a+b;
	}
	
	long add(long a, int b) {
		System.out.print("long add(long a, int b) - ");
		return a+b;
	}
	long add(long a, long b) {
		System.out.print("long add(long a, long b) - ");
		return a+b;
	}
	int add(int[] a ) {
		System.out.print("int add(int[] a) - ");
		int result = 0;
		for(int i=0; i < a.length;i++) {
			result +=a[i];
		}
		return result;
	}
}
int add(int a, int b) -mm.add(3, 3) 결과:6
long add(long a, int b) - mm.add(3L, 3) 결과: 6
long add(int a, long b) - mm.add(3, 3L) 결과: 6
long add(long a, long b) - mm.add(3L, 3L) 결과: 6
int add(int[] a) - mm.add(a) 결과: 600

 

 

 

public class VarArgsEx {
	public static void main(String[] args) {
		String[] strArr = { "100", "200", "300"	};
		
		System.out.println(concatenate("", "100", "200", "300"));
		System.out.println(concatenate("-", strArr));
		System.out.println(concatenate(",", new String[] {"1", "2", "3"}));
		System.out.println("["+concatenate(",", new String[0])+"]");
		System.out.println("["+concatenate(",")+"]");
	}
	
	static	String concatenate(String delim, String...args) {
		String result = "";
		
		for(String str : args) {
			result += str + delim;
		}
		
		return result;
	}
//	
//	static String concatenate(String...strings args) {
//		return concatenate("", args);
//	}
	
}
100200300
100-200-300-
1,2,3,
[]
[]

 

 

 

public class ConstructorTest {
	public static void main(String[] args) {
		Data1 d1 = new Data1();
		Data2 d2 = new Data2();	//오류를 고치기 위해 int타입의 인자를 기입해주면된다.
		System.out.println(d2.value);
	}
}

class Data1 {
	int value;
	Data1() {} //생성자가 기본으로 만들어져있음
	
}

class Data2 {
	int value;
	Data2(){}  //6번줄의 오류를 고치기 위해생성자를만들어줌 즉 초기화를시킴
	
	Data2(int x) {
		value = x;
	}
}
0

 

 

 

class Car {
	String color;
	String gearType;
	int door;
	
	Car(){}
	Car(String c, String g, int d) {
		color = c;
		gearType = g;
		door = d;
	}
}
public class CarTest {
	public static void main(String[] args) {
		Car c1 = new Car();
		c1.color	= "white";
		c1.gearType	= "auto";
		c1.door 	= 4;
		
		Car c2	= new Car("white", "auto", 4);
		
		System.out.println("c1의 color=" + c1.color + ", gearType=" +c1.gearType+ ", door"+c1.door);
		System.out.println("c2의 color=" + c2.color + ", gearType=" +c2.gearType+ ", door"+c2.door);
	}
}
c1의 color=white, gearType=auto, door4
c2의 color=white, gearType=auto, door4

 

 

 

class Car {
	String color;
	String gearType;
	int door;
	
	Car() {
		this("white", "auto", 4);
	}

	Car(String color) {
			this(color, "auto", 4);
		}
		Car(String color, String gearType, int door) {
			this.color = color;
			this.gearType = gearType;
			this.door = door;
		}
		Car(Car c) {
			color = c.color;
			gearType = c.gearType;
			door = c.door;
		}
}

public class CarTest2 {
	public static void main(String[] args) {
		Car c1 = new Car();
		Car c2 = new Car("blue");
		
		System.out.println("c1의 color=" + c1.color + ", gearType=" + c1.gearType+ ", door="+c1.door);
		System.out.println("c2의 color=" + c2.color + ", gearType=" + c2.gearType+ ", door="+c2.door);
		
	}
}
c1의 color=white, gearType=auto, door=4
c2의 color=blue, gearType=auto, door=4

 

 

 

class Car {
	String color;
	String gearType;
	int door;

	Car() {
		this("white", "auto", 4);
	}

	Car(Car c) {
		color = c.color;
		gearType = c.gearType;
		door = c.door;
	}

	Car(String color, String gearType, int door) {
		this.gearType = gearType;
		this.door = door;
	}
}

class CarTest3 {
	public static void main(String[] args) {
		Car c1 = new Car();
		Car c2 = new Car(c1);
		System.out.println("c1의 color=" + c1.color + ", gearType=" + c1.gearType + ", door" + c1.door);
		System.out.println("c1의 color=" + c1.color + ", gearType=" + c1.gearType + ", door" + c1.door);
		c1.door = 100;
		System.out.println("c1.door=100; 수행 후");
		System.out.println("c1의 color=" + c1.color + ", gearType=" + c1.gearType + ", door=" + c1.door);
		System.out.println("c2의 color=" + c2.color + ", gearType=" + c2.gearType + ", door=" + c2.door);
	}
}
c1의 color=null, gearType=auto, door4
c1의 color=null, gearType=auto, door4
c1.door=100; 수행 후
c1의 color=null, gearType=auto, door=100
c2의 color=null, gearType=auto, door=4

 

public class ArrayEx01 {
	public static void main(String[] args) {
		int[] score = new int[5];
		int k = 1;

		score[0] = 50;
		score[1] = 60;
		score[k + 1] = 70; // score[2] = 70
		score[3] = 80;
		score[4] = 90;

		int tmp = score[k + 2] + score[4]; // int tmp = score[3] + score[4]

		// for문으로 배열의 모든 요소를 출력한다.
		for (int i = 0; i < 5; i++) {
			System.out.printf("score[%d]:%d%n", i, score[i]);
		}
			System.out.printf("tmp:%d%n", tmp);
			System.out.printf("score[%d]:%d%n", 7, score[7]);// index의 범위를 벗어난 값);
		}
	}
score[0]:50
score[1]:60
score[2]:70
score[3]:80
score[4]:90
tmp:170
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 7
	at a210712.ArrayEx01.main(ArrayEx01.java:23)

 

 

 

import java.util.Arrays;

//import java.util.*;	// Arrays.toString()을 사용하기 위해 추가

public class ArrayEx02 {
	public static void main(String[] args) {
		int[] iArr1 = new int[10];
		int[] iArr2 = new int[10];
//		int[] iArr3 = new int[] {100, 95, 80, 70, 60};
		int[] iArr3 = {100, 95, 80, 70, 60};
		char[] chArr = {'a', 'b', 'c', 'd'};
		
		for(int i=0; i < iArr1.length ; i++) {
			iArr1[i] = i +1; // 1~10의 숫자를 순서대로 배열에 넣는다.
			
		}
		for (int i=0; i< iArr2.length ; i++) {
			iArr2[i] = (int)(Math.random()*10) + 1;
		}	
			// 배열에 저장된 값들을 출력한다.
			for(int i=0; i <iArr1.length;i++) {
				System.out.print(iArr1[i]+",");
			}
			System.out.println();System.out.println(Arrays.toString(iArr2));
			System.out.println();System.out.println(Arrays.toString(iArr3));
			System.out.println();System.out.println(Arrays.toString(chArr));
			System.out.println();System.out.println(iArr3);
			System.out.println();System.out.println(chArr);
		}
	}
1,2,3,4,5,6,7,8,9,10,
[5, 7, 10, 6, 3, 5, 3, 1, 8, 2]

[100, 95, 80, 70, 60]

[a, b, c, d]

[I@6d06d69c

abcd

 

 

 

public class ArrayEx03 {
	public static void main(String[] args) {
		int[] arr = new int[5];
		
		// 배열 arr에 1~5를 저장한다.
		for (int i = 0; i < arr.length; i++) {
			arr[i] = i + 1; // 1 2 3 4 5
		}
		System.out.println("[변경전]");
		System.out.println("arr.length: " + arr.length);

		for (int i = 0; i < arr.length; i++) {
			System.out.println("arr[" + i + "]:" + arr[i]);
		}
		int[] tmp = new int[arr.length * 2];

		for (int i = 0; i < arr.length; i++) {
			tmp[i] = arr[i];
		}
		arr = tmp;
		System.out.println("[변경후]");
		System.out.println("arr.length : " + arr.length);

		for (int i = 0; i < arr.length; i++) {
			System.out.println("arr[" + i + "]:" + arr[i]);
		}
	}
}
[변경전]
arr.length: 5
arr[0]:1
arr[1]:2
arr[2]:3
arr[3]:4
arr[4]:5
[변경후]
arr.length : 10
arr[0]:1
arr[1]:2
arr[2]:3
arr[3]:4
arr[4]:5
arr[5]:0
arr[6]:0
arr[7]:0
arr[8]:0
arr[9]:0

 

 

 

public class ArrayEx04 {
	public static void main(String[] args) {
		char[] abc = { 'A', 'B', 'C', 'D' };
		char[] num = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9'};
		System.out.println(abc);
		System.out.println(num);
		
		// 배열 abc와 num을 붙여서 하나의 배열(result)로 만든다.
		char[] result = new char[abc.length+num.length];
		System.arraycopy(abc, 0, result, 0, abc.length);
		System.arraycopy(num, 0, result, abc.length, num.length);
		System.out.println(result);
		
		// 배열 abc를 배열 num의 첫 번째 위치부터 배열 abc의 길이만큼 복사
		System.arraycopy(abc,  0,  num,  0,  abc.length);
		System.out.println(num);
		
		// number의 인덱스6 위치에 3개를 보사
		System.arraycopy(abc, 0, num, 6, 3);
		System.out.println(num);
	}
}
ABCD
0123456789
ABCD0123456789
ABCD456789
ABCD45ABC9

 

 

 

public class ArrayEx05 {
	public static void main(String[] args) {
		int sum = 0;
		float average = 0f;

		int[] score = { 100, 88, 100, 100, 90 };

		for (int i = 0; i < score.length; i++) {
			sum += score[i];
		}

		average = sum / (float) score.length;
		System.out.println("총점 : " + sum);
		System.out.println("평균 : " + average);
	}
}
총점 : 478
평균 : 95.6

 

 

public class ArrayEx06 {
	public static void main(String[] args) {
		int[] score = { 79, 88, 91, 33, 100, 55, 95 };

		int max = score[0];
		int min = score[0];

		for (int i = 1; i < score.length; i++) {
			if (score[i] > max) {
				max = score[i];
			} else if (score[i] < min) {
				min = score[i];
			}
		} // end of for
		System.out.println("최대값 :" + max);
		System.out.println("최소값 :" + min);
	} // end of main
}// end of class
최대값 :100
최소값 :33

 

 

public class ArrayEx07 {
	public static void main(String[] args) {
		int[] numArr = new int[10];

		for (int i = 0; i < numArr.length; i++) {
			numArr[i] = i;
			System.out.print(numArr[i]);
		}
		System.out.println();

		for (int i = 0; i < 100; i++) {
			int n = (int) (Math.random() * 10);
			int tmp = numArr[0];
			numArr[0] = numArr[n];
			numArr[n] = tmp;
		}
		for (int i = 0; i < numArr.length; i++)
			System.out.print(numArr[i]);
	}
}
0123456789
0324879615

 

 

public class ArrayEx08 {
	public static void main(String[] args) {
		int[] ball = new int[45];

		for (int i = 0; i < ball.length; i++)
			ball[i] = i + 1;

		int temp = 0;
		int j = 0;

		for (int i = 0; i < 6; i++) {
			j = (int) (Math.random() * 45);
			temp = ball[i];
			ball[i] = ball[j];
			ball[j] = temp;
		}
		for (int i = 0; i < 6; i++)
		System.out.printf("ball[%d]=%d%n", i, ball[i]);
	}
}
ball[0]=13
ball[1]=23
ball[2]=9
ball[3]=45
ball[4]=27
ball[5]=4

 

 

 

import java.util.*;

public class ArrayEx09 {
	public static void main(String[] args) {
		int[] code = {-4, -1, 3, 6, 11};
		int[] arr = new int[10];
		
		for(int i=0; i < arr.length ; i++) {
			int tmp = (int)(Math.random() * code.length);
			arr[i] = code[tmp];
		}
		
		System.out.println(Arrays.toString(arr));
	}
}
[11, 6, 11, 11, 11, 3, 11, 6, -1, 11]

 

 

 

 

public class ArrayEx10 {
	public static void main(String[] args) {
		int[] numArr = new int[10];

		for (int i = 0; i < numArr.length; i++) {
			System.out.print(numArr[i] = (int) (Math.random() * 10));
		}
		System.out.println();

		for (int i = 0; i < numArr.length - 1; i++) {
			boolean changed = false;

			for (int j = 0; j < numArr.length - 1 - i; j++) {
				if (numArr[j] > numArr[j + 1]) {
					int temp = numArr[j];
					numArr[j] = numArr[j + 1];
					numArr[j + 1] = temp;
					changed = true;
				}
			}

			if (!changed)
				break;

			for (int k = 0; k < numArr.length; k++)
				System.out.print(numArr[k]);
			System.out.println();
		}

	}
}
3889633208
3886332089
3863320889
3633208889
3332068889
3320368889
3203368889
2033368889
0233368889

 

 

public class ArrayEx11 {
	public static void main(String[] args) {
		int[] numArr = new int[10];
		int[] counter = new int[10];
		
		for(int i=0; i < numArr.length ; i++) {
			numArr[i] = (int)(Math.random() * 10);
			System.out.println(numArr[i]);
		}
		System.out.println();
		
		for(int i=0; i < numArr.length ; i++) {
			counter[numArr[i]]++;
		}
		
		for (int i=0; i < numArr.length ; i++){
			System.out.println( i +"의 개수 :"+ counter[i]);
		}
	}
}
8953030234
0의 개수 :2
1의 개수 :0
2의 개수 :1
3의 개수 :3
4의 개수 :1
5의 개수 :1
6의 개수 :0
7의 개수 :0
8의 개수 :1
9의 개수 :1

 

 

 

public class ArrayEx12 {
	public static void main(String[] args) {
		String[] names = { "Kim", "Park", "Yi" };

		for (int i = 0; i < names.length; i++)
			System.out.println("names[" + i + "]:" + names[i]);

		String tmp = names[2];
		System.out.println("tmp:" + tmp);
		names[0] = "Yu";

		for (String str : names)
			System.out.println(str);
	}
}
names[0]:Kim
names[1]:Park
names[2]:Yi
tmp:Yi
Yu
Park
Yi

 

 

public class ArrayEx13 {
	public static void main(String[] args) {
		char[] hex = { 'C', 'A', 'F', 'E'};
		
		String[] binary = { "0000", "0001", "0010", "0011",
							"0100", "0101", "0110", "0111",
							"1000",	"1001",	"1001",	"1011",
							"1100",	"1101",	"1110",	"1111"};
		
		String result="";
		for(int i=0; i < hex.length ; i++) {
			if(hex[i] >='0' && hex[i] <='9')	{
				result +=binary[hex[i]-'0'];
			}else {
				result +=binary[hex[i]-'A'+10];
			}
		
		}
		System.out.println("hex:"+ new String(hex));
		System.out.println("binary:"+result);
	}
}
hex:CAFE
binary:1100100111111110

 

 

public class ArrayEx14 {
	public static void main(String[] args) {
		String src = "ABCDE";

		for (int i = 0; i < src.length(); i++) {
			char ch = src.charAt(i); // src의 i번째 문자를 ch에 저장
			System.out.println("src.charAt(" + i + "):" + ch);
		}
			// String을 char[]로 변환
			char[] chArr = src.toCharArray();

			// char배열(char[])을 출력
			System.out.println(chArr);
		}
	}
src.charAt(0):A
src.charAt(1):B
src.charAt(2):C
src.charAt(3):D
src.charAt(4):E
ABCDE

 

 

public class ArrayEx15 {
	public static void main(String[] args) {
		String source = "SOSHELP";
		String[] morse = { ".-", "-...", "-.-", "-..", ".",
				 "..-.", "--.", "....", "..", ".---",
				 "-.-", ".-..", "--", "-.", "---",
				 ".--.", "--.-", ".-.", "...", "-",
				 "..-", "...-", ".--", "-..-", "-.--",
				 "--.."};
		
		String result="";
		
		for(int i=0; i< source.length(); i++) {
			result+=morse[source.charAt(i)-'A'];
			}
		System.out.println("source:"+ source);
		System.out.println("morse:"+result);
		}
	}
source:SOSHELP
morse:...---.........-...--.

 

 

 

public class ArrayEx16 {
	public static void main(String[] args) {
		System.out.println("매개변수의 개수:"+args.length);
		for(int i=0; i<args.length;i++) {
			System.out.println("args[" + i + "] = \""+ args[i] + "\"");
		}
	}
}
매개변수의 개수:3
args[0] = "abc"
args[1] = "123"
args[2] = "Hello world"

 

 

 

public class ArrayEx17 {
	public static void main(String[] args) {
		if (args.length !=3) {
			System.out.println("usage: java ArrayEx17 NUM1 OP NUM2");
			System.exit(0);
		}
		
		int num1 = Integer.parseInt(args[0]);
		char op = args[1].charAt(0);
		int num2 = Integer.parseInt(args[2]);
		int result = 0;
		
		switch(op) {
		case '+':
		result = num1 + num2;
			break;
			
		case '-':
		result = num1 - num2;
			break;
		
		case 'x':
			result = num1 * num2;
			break;
			
		case '/':
			result = num1 / num2;
			break;
		default :
			System.out.println("지원되지 않는 연산입니다.");
		}
		System.out.println("결과"+result);
		}
	}
(7+6을 입력함)
결과13

 

 

 

public class ArrayEx18 {
	public static void main(String[] args) {
		int[][] score = { 
				{ 100, 100, 100 }, 
				{ 20, 20, 20 }, 
				{ 30, 30, 30 }, 
				{ 40, 40, 40 } };
		int sum = 0;

		for (int i = 0; i < score.length; i++) {
			for (int j = 0; j < score[i].length; j++) {
				System.out.printf("score[%d][%d]=%d%n", i, j, score[i][j]);
			}
		}
		for (int[] tmp : score) {
			for (int i : tmp) {
				sum += i;
			}
		}
		System.out.println("sum=" + sum);
	}
}
score[0][0]=100
score[0][1]=100
score[0][2]=100
score[1][0]=20
score[1][1]=20
score[1][2]=20
score[2][0]=30
score[2][1]=30
score[2][2]=30
score[3][0]=40
score[3][1]=40
score[3][2]=40
sum=570

 

 

public class ArrayEx19 {
	public static void main(String[] args) {
		int[][] score = {
				{100, 100, 100}
				, {20, 20, 20}
				, {30, 30, 30}
				, {40, 40, 40}
				, {50, 50, 50}
		};
		// 과목별 총점
		int korTotal = 0, engTotal = 0, mathTotal = 0;
		
		System.out.println("번호	국어	영어	수학	총점	평균 ");
		System.out.println("=============================================");
		
		for(int i=0; i< score.length;i++) {
			int sum = 0;
			float avg = 0.0f;
			
			korTotal += score[i][0];
			engTotal += score[i][1];
			mathTotal += score[i][2];
			System.out.printf("%3d", i+1);
			
			for(int j=0; j <score[i].length;j++) {
				sum += score[i][j];
				System.out.printf("%5d", score[i][j]);
			}
			
			avg = sum/(float)score[i].length; //평균계산
			System.out.printf("%5d %5.1f%n", sum, avg);
		}
		System.out.println("=====================================");
		System.out.printf("총점:%d %4d %4d%n",korTotal,engTotal,mathTotal);
	}
}
번호	국어	영어	수학	총점	평균 
=============================================
  1  100  100  100  300 100.0
  2   20   20   20   60  20.0
  3   30   30   30   90  30.0
  4   40   40   40  120  40.0
  5   50   50   50  150  50.0
=====================================
총점:240  240  240

 

 

public class MultiArrEx1 {
	public static void main(String[] args) {
		final int SIZE = 10;
		int x = 0, y = 0;
		
		char[][] board = new char[SIZE][SIZE];
		byte[][] shipBoard = {
				// 1 2 3 4 5 6 7 8 9
				{ 0, 0, 0, 0, 0, 0, 1, 0, 0, }, // 1
				{ 1, 1, 1, 1, 0, 0, 1, 0, 0, }, // 2
				{ 0, 0, 0, 0, 0, 0, 1, 0, 0, }, // 3
				{ 0, 0, 0, 0, 0, 0, 1, 0, 0, }, // 4
				{ 0, 0, 0, 0, 0, 0, 0, 0, 0, }, // 5
				{ 1, 1, 0, 1, 0, 0, 0, 0, 0, }, // 6
				{ 0, 0, 0, 1, 0, 0, 0, 0, 0, }, // 7
				{ 0, 0, 0, 1, 0, 0, 0, 0, 0, }, // 8
				{ 0, 0, 0, 0, 0, 1, 1, 1, 0, }, // 9
		};
		
		// 1행에 행번호를, 1열에 열번호를 저장한다.
		for(int i=1; i<SIZE; i++)
			board[0][i] = board[i][0] = (char)(i+'0');
		
		Scanner scanner = new Scanner(System.in);
		
		while(true) {
			System.out.println("좌표를 입력하세요.(종료는 00)>");
			String input = scanner.nextLine();
			
			if(input.length()==2) {
			x = input.charAt(0) - '0';
			y = input.charAt(1) - '0';
			
			if(x==0 && y==0)
				break;
			}
			
			if(input.length() !=2 || x<=0 || x>=SIZE||y<=0||y>=SIZE) {
				System.out.println("잘못된 입력입니다. 다시 입력해주세요.");
				continue;
			}
			
			// shipBoard[x-1][y-1]의 값이 1이면, 'O'을 board[x][y]에 저장한다.
			board[x][y] =shipBoard[x-1][y-1] ==1 ? 'O' : 'X';
			
			//	배열 board의 내용을 화면에 출력한다.
			for(int i=0;i<SIZE;i++)
				System.out.println(board[i]); // board[i]는 1차원 배열
			System.out.println();
			}
		scanner.close();
		}
	}
좌표를 입력하세요.(종료는 00)>
33

 

 

 

import java.util.Scanner;

public class MultiArrEx2 {
	public static void main(String[] args) {
		final int SIZE = 5;
		int x = 0, y = 0, num = 0;
		
		int[][] bingo = new int[SIZE][SIZE];
		Scanner scanner = new Scanner(System.in);
		
		//배열의 모든 요소를 1부터 SIZE*SIZE까지의 숫자로 초기화
		for(int i=0;i<SIZE;i++)
			for(int j=0;j<SIZE;j++)
				bingo[i][j] = i*SIZE + j +1;
		
		// 배열에 저장된 값을 뒤섞는다.(suffle)
		for(int i=0;i<SIZE;i++) {
			for(int j=0;j<SIZE;j++) {
			x = (int)(Math.random() * SIZE);
			y = (int)(Math.random() * SIZE);
			
			// bingo[i][j]와 임의로 선택된 값(bingo[x][y])을 바꾼다.
			int tmp = bingo[i][j];
			bingo[i][j] = bingo[x][y];
			bingo[x][y] = tmp;
		}
	
	}
		do {
			for(int i=0;i<SIZE;i++) {
				for(int j=0;j<SIZE;j++)
					System.out.printf("%2d ", bingo[i][j]);
				System.out.println();
		}
			System.out.println();
			
			System.out.printf("1~%d의 숫자를 입력하세요.(종료:0)>", SIZE*SIZE);
			String tmp = scanner.nextLine(); // 화면에서 입력받은 내용을 tmp에 저장
			num = Integer.parseInt(tmp);	// 입력받은 문자열(tmp)를 숫자로 변환
			
			// 입력받은 숫자와 같은 숫자가 저장된 요소를 찾아서 0을저장
			outer:
				for(int i=0;i<SIZE;i++) {
					for(int j=0;j<SIZE;j++) {
						if(bingo[i][j]==num) {
							bingo[i][j] = 0;
							break outer; // 2중 반복문을 벗어난다.
						}
					}
				}
			
		} while(num!=0);
		scanner.close();
	} // main의 끝
}
11  8 25  5  3 
 1 10 14 24 20 
16 13 22 18 17 
 6 19 15 21  9 
 2 12  7 23  4 

1~25의 숫자를 입력하세요.(종료:0)>11
 0  8 25  5  3 
 1 10 14 24 20 
16 13 22 18 17 
 6 19 15 21  9 
 2 12  7 23  4 

1~25의 숫자를 입력하세요.(종료:0)>8
 0  0 25  5  3 
 1 10 14 24 20 
16 13 22 18 17 
 6 19 15 21  9 
 2 12  7 23  4 

1~25의 숫자를 입력하세요.(종료:0)>0

 

 

 

public class MultiArrEx3 {
	public static void main(String[] args) {
		int[][] m1 = {
				{1, 2, 3},
				{4, 5, 6}
		};
	
		int[][] m2 = {{1, 2},
				{3, 4},
				{5, 6}
	};
	
	final int ROW	= m1.length;
	final int COL	= m2[0].length;
	final int M2_ROW= m2.length;
	
	int[][] m3 = new int[ROW][COL];
	
	// 행렬곱 m1 x m2의 결과를 m3에 저장
	for(int i=0;i<ROW;i++)
		for(int j=0;j<COL;j++)
			for(int k=0;k<M2_ROW;k++)
				m3[i][j] += m1[i][k] * m2[k][j];
	
	// 행렬 m3를 출력
	for(int i=0;i<ROW;i++) {
		for(int j=0;j<COL;j++) {
			System.out.printf("%3d ", m3[i][j]);
		}
		System.out.println();
		
		}
	} // main의 끝

}
 22  28 
 49  64

 

 

import java.util.Scanner;

public class MultiArrEx4 {
	public static void main(String[] args) {
		String[][] words = {
				{"chair", "의자"},
				{"computer", "컴퓨터"},
				{"integer","정수"}
		};
	
		Scanner scanner = new Scanner(System.in);
		
		for(int i=0;i<words.length;i++) {
			System.out.printf("Q%d. %s의 뜻은", i+1, words[i][0]);
			
			String tmp = scanner.nextLine();
			
			if(tmp.contentEquals(words[i][1])) {
				System.out.printf("정답입니다.%n%n");
			} else {
				System.out.printf("틀렸습니다 정답은 %s입니다.%n%n",words[i][i]);
			}
		}scanner.close(); // for
	} // main의 끝
}
Q1. chair의 뜻은액자
틀렸습니다 정답은 chair입니다.

Q2. computer의 뜻은컴퓨터
정답입니다.

Q3. integer의 뜻은정수
정답입니다.

 

찾으려면 ctrl+F한 뒤 class이름을 검색하자

각 calss밑에는 실행 시 나오는 console내용이 있다.

public class FlowEx01 {
	public static void main(String[] args) {
		int x = 0;
		System.out.printf("x=%d 일 때, 참인 것은%n", x);

		if (x == 0)
			System.out.println("x==0");
		if (x != 0)
			System.out.println("x!=0"); // f
		if (!(x == 0))
			System.out.println("!(x==0)"); // f
		if (!(x != 0))
			System.out.println("!(x!=0)");

		x = 1;
		System.out.printf("x=%d 일 때, 참인 것은 %n", x);

		if (x == 0)
			System.out.println("x==0"); // f
		if (x != 0)
			System.out.println("x!=0");
		if (!(x == 0))
			System.out.println("!(x==0)");
		if (!(x != 0))
			System.out.println("!(x!=0)"); // f

		if (true) {
			System.out.println("");
		}
	}
}
x=0 일 때, 참인 것은
x==0
!(x!=0)
x=1 일 때, 참인 것은 
x!=0
!(x==0)

 

 

public class FlowEx02 {
	public static void main(String[] args) {
		int input;

		System.out.print("숫자를 하나 입력하세요.>");

		Scanner scanner = new Scanner(System.in);
		String tmp = scanner.nextLine();
		input = Integer.parseInt(tmp);

		if (input == 0) {
//			System.out.println("입력하신 숫자는 0입니다.");
			System.out.println("입력하신 숫자는 0입니다.");
		}

		else if (input % 2 == 0) {
			System.out.println("입력하신 숫자는 짝수입니다.");
		}

		else if (input % 2 == 1) {
			// System.out.println("입력하신 숫자는 0이 아닙니다.");
//		System.out.printf("입력하신 숫자는 %d입니다.", input);
			System.out.println("입력하신 숫자는 홀수입니다.");

			scanner.close();
		}
	}
}
0입력시

숫자를 하나 입력하세요.>0
입력하신 숫자는 0입니다.
숫자를 하나 입력하세요.>1
입력하신 숫자는 홀수입니다.

 

 

public class FlowEx03 {
	public static void main(String[] args) {
		System.out.println("숫자를 하나 입력하세요.>");
		
		Scanner scanner = new Scanner(System.in);
		int input = scanner.nextInt();
		
		if(input==0) {
			System.out.println("입력하신 숫자는 0입니다.");
		} else {
			System.out.println("입력하신 숫자는 0이 아닙니다.");
		}
		scanner.close();
	}
}
숫자를 하나 입력하세요.>
1
입력하신 숫자는 0이 아닙니다.

 

 

public class FlowEx04 {
	public static void main(String[] args) {
		int score = 0;
		char grade = ' ';

		System.out.print("점수를 입력하세요.>");
		Scanner scanner = new Scanner(System.in);
		score = scanner.nextInt();

		if (score >= 90) {
			grade = 'A';
		} else if (score >= 80) {
			grade = 'B';
		} else if (score >= 70) {
			grade = 'C';
		} else {
			grade = 'D';
		}


		System.out.println("당신의 학점은 "+ grade +"입니다.");
		scanner.close();
	}
}
점수를 입력하세요.>30
당신의 학점은 D입니다.

 

 

public class FlowEx05 {
	public static void main(String[] args) {
		int score = 0;
		char grade = ' ', opt = '0';

		System.out.print("점수를 입력해주세요.>");

		Scanner scanner = new Scanner(System.in);
		score = scanner.nextInt();

		System.out.printf("당신의 점수는 %d입니다.%n", score);

		if (score >= 90) {
			grade = 'A';
			if (score >= 98) {
				opt = '+';
			} else if (score < 94) {
				opt = '-';
			}
		} else if (score >= 80) {
			grade = 'B';
			if (score >= 88) {
				opt = '-';
			}
		} else {
			grade = 'C';
		}
		System.out.printf("당신의 학점은 %c%c입니다.%n", grade, opt);
		scanner.close();
	}
}
점수를 입력해주세요.>85
당신의 점수는 85입니다.
당신의 학점은 B0입니다.

 

 

public class FlowEx06 {
	public static void main(String[] args) {
		System.out.println("현재 월을 입력하세요.>");
		
		Scanner scanner = new Scanner(System.in);
		int month = scanner.nextInt();
		
		switch(month) {
		case 3:
		case 4:
		case 5:
			System.out.println("현재의 계절은 봄입니다.");
			break;
		case 6: case 7: case 8:
			System.out.println("현재의 계절은 여름입니다.");
			break;
		case 9: case 10: case 11:
			System.out.println("현재의 계절은 가을입니다.");
			break;
			default:
			case 12: case 1: case 2:
				System.out.println("현재의 계절은 겨울입니다.");
		}
		scanner.close();
	}// main의 끝
}
현재 월을 입력하세요.>
7
현재의 계절은 여름입니다.

 

 

public class FlowEx07 {
	public static void main(String[] args) {
		System.out.print("가위(1),바위(2),보(3) 중 하나를 입력하세요.>");
		
		Scanner scanner = new Scanner(System.in);
		int user = scanner.nextInt();
		int com = (int)(Math.random() * 3) +1;
		
		System.out.println("당신은 "+ user +"입니다.");
		System.out.println("컴은 "+ com +"입니다.");
		
		switch(user-com) {
		case 2: case -1:
			System.out.println("당신이 졌습니다.");
			break;
		case 1: case -2:
			System.out.println("당신이 이겼습니다.");
			break;
		case 0:
			System.out.println("비겼습니다.");
			break;
		}
		scanner.close();
	}//main의 끝
}
가위(1),바위(2),보(3) 중 하나를 입력하세요.>1
당신은 1입니다.
컴은 1입니다.
비겼습니다.

 

 

public class FlowEx08 {
	public static void main(String[] args) {
		System.out.println("당신의 주민번호를 입력하세요. (011231-1111222)>");
		
		Scanner scanner = new Scanner(System.in);
		String regNo = scanner.nextLine();
		
		char gender = regNo.charAt(7);
		
		switch(gender) {
		case '1': case '3':
			System.out.println("당신은 남자입니다.");
			break;
		case '2': case '4':
			System.out.println("당신은 여자입니다.");
			break;
			default:
				System.out.println("유효하지 않은 주민등록번호입니다.");
		}
		scanner.close();
	}// main의 끝

}
당신의 주민번호를 입력하세요. (011231-1111222)>
830721-1351228
당신은 남자입니다.

 

public class FlowEx09 {
	public static void main(String[] args) {
		char grade = ' ';
		
		System.out.print("당신의 점수를 입력하세요.(1~100)>");
		
		Scanner scanner = new Scanner(System.in);
		int score = scanner.nextInt();
		
		switch(score) {
		case 100: case 99: case 98: case 97: case 96:
		case 95: case 94: case 93: case 92: case 91: case 90:
		grade = 'A';
		break;
		case 89: case 88: case 87: case 86: case 85:
		case 84: case 83: case 82: case 81: case 80:
		grade = 'B';
		break;
		case 79: case 78: case 77: case 76: case 75:
		case 74: case 73: case 72: case 71: case 70:
		grade = 'C';
		break;
		default :
			grade = 'F';
			scanner.close();
		} // end of switch
		System.out.println("당신의 학점은 "+ grade +"입니다.");
	}
}
당신의 점수를 입력하세요.(1~100)>99
당신의 학점은 A입니다.

 

 

public class FlowEx10 {
	public static void main(String[] args) {
		int score = 0;
		char grade = ' ';
		
		System.out.println("당신의 점수를 입력하세요.(1~10)>");
		
		Scanner scanner = new Scanner(System.in);
		String tmp = scanner.nextLine();
		score = Integer.parseInt(tmp);
		
		switch(score/10) {
		case 10:
		case 9:
			grade = 'A';
			break;
		case 8:
			grade = 'B';
			break;
		case 7 :
			grade = 'C';
			break;
			default :
				grade = 'F';
		}// end of switch
		scanner.close();
		System.out.println("당신의 학점은 "+ grade +"입니다.");
	}//main의 끝
}
당신의 점수를 입력하세요.(1~10)>
5
당신의 학점은 F입니다.

 

 

 

public class FlowEx11 {
	public static void main(String[] args) {
		System.out.print("당신의 주민번호를 입력하세요. (011231-1111222)>");
		
		Scanner scanner = new Scanner(System.in);
		String regNo = scanner.nextLine();
		char gender = regNo.charAt(7);
		
		switch(gender) {
		case '1': case '3':
			switch(gender) {
			case '1':
				System.out.println("당신은 2000년 이전에 출생한 남자입니다.");
				break;
			case '3':
				System.out.println("당신은 2000년 이후에 출생한 남자입니다.");
			}
			break;
		case '2': case '4':
			switch(gender) {
			case '2':
				System.out.println("당신은 2000년 이전에출생한 여자입니다.");
				break;
			case '4':
				System.out.println("당신은 2000년 이후에 출생한 여자입니다.");
				break;
			}
			break;
			default:
				System.out.println("유효하지 않은 주민등록번호입니다.");

		}
		scanner.close();
	}//main의 끝
}
당신의 주민번호를 입력하세요. (011231-1111222)>354321-3205664
당신은 2000년 이후에 출생한 남자입니다.

 

 

public class FlowEx12 {
	public static void main(String[] args) {
		int i = 1;
		for (; i <= 5; i++) {
			System.out.println(i);// i의 값을 출력한다
		}

		for (; i <= 5;) {
			System.out.println(i);// i의 값을 출력한다
			i++;
		}

		for (; i <= 5; i++) {
			System.out.print(i);
		}

		System.out.println();
	}
}

 

 

 

public class FlowEx12 {
		public static void main(String[] args) {			
			for (int i = 1; i <= 5; i++) {
				System.out.println(i);
			}

			for (int i = 1; i <= 5; i++) {
				System.out.print(i);
			}

			System.out.println();
		}

	}
1
2
3
4
5
12345

 

 

 

public class FlowEx13 {
	public static void main(String[] args) {
		// 1부터 10까지의 합 구하기
		int sum = 0;	// 합계를 저장하기 위한 변수

		for (int i = 1; i <= 10; i++) {
			sum += i; //	sum = sum + i;
			System.out.printf("1부터 %d 까지의 합: %2d%n", i, sum);
		}
	}
}
1부터 1 까지의 합:  1
1부터 2 까지의 합:  3
1부터 3 까지의 합:  6
1부터 4 까지의 합: 10
1부터 5 까지의 합: 15
1부터 6 까지의 합: 21
1부터 7 까지의 합: 28
1부터 8 까지의 합: 36
1부터 9 까지의 합: 45
1부터 10 까지의 합: 55

 

 

 

public class FlowEx14 {
	public static void main(String[] args) {
		for (int i = 1, j = 10; i <= 10; i++, j--) { // 반복횟수 가급적 for문에서는 시작의 변수는 하나만
			System.out.printf("%d \t %d%n", i, j);
		}

		for (int i = 1; i <= 10; i++) {

		}

		for (int i = 0; i < 10; i++) {
			
		}
	}
}
1 	 10
2 	 9
3 	 8
4 	 7
5 	 6
6 	 5
7 	 4
8 	 3
9 	 2
10 	 1

 

 

public class FlowEx15 {
	public static void main(String[] args) {
//		 ctrl + F find/replace
		System.out.println("i \t 2*i \t 2*i-1 \t i*i \t 11-i \t i%3 \t i/3");
		System.out.println("--------------------------------------");
		
		for(int i=1;i<=10;i++)
			System.out.printf("%d \t %d \t %d \t %d \t %d \t %d \t %d%n ", i, 2*i, 2*i-1, i*i, 11-i, i%3, i/3);
	}
}
i 	 2*i 	 2*i-1 	 i*i 	 11-i 	 i%3 	 i/3
--------------------------------------
1 	 2 	 1 	 1 	 10 	 1 	 0
 2 	 4 	 3 	 4 	 9 	 2 	 0
 3 	 6 	 5 	 9 	 8 	 0 	 1
 4 	 8 	 7 	 16 	 7 	 1 	 1
 5 	 10 	 9 	 25 	 6 	 2 	 1
 6 	 12 	 11 	 36 	 5 	 0 	 2
 7 	 14 	 13 	 49 	 4 	 1 	 2
 8 	 16 	 15 	 64 	 3 	 2 	 2
 9 	 18 	 17 	 81 	 2 	 0 	 3
 10 	 20 	 19 	 100 	 1 	 1 	 3

 

 

public class FlowEx16 {
//반피라미드형
	public static void main(String[] args) {

		for (int i = 1; i <= 5; i++) {

			for (int j = 1; j <= i; j++) {
				
				System.out.printf("*");

			}
			System.out.println();
		}
	}

}
*
**
***
****
*****

 

 

public class FlowEx17 {
	public static void main(String[] args) {
		int num = 0;
		
		System.out.print("*을 출력할 라인의 수를 입력하세요.>");
		
		Scanner scanner = new Scanner(System.in);
		String tmp = scanner.nextLine();
		num = Integer.parseInt(tmp);
		
		for(int i =0; i<num;i++) {
			for(int j=0; j<=i;j++) {
				System.out.print("*");
			}
			System.out.println();
		}
		scanner.close();
	}
}
*을 출력할 라인의 수를 입력하세요.>10
*
**
***
****
*****
******
*******
********
*********
**********

 

 

public class FlowEx18 {
	public static void main(String[] args) {
		for(int i=2;i<=9;i++) {	//8
			for(int j=1;j<=9;j++) {	//9
				System.out.printf("%d x %d = %d%n", i, j, i*j); // 72
			}
		}
	}
}
2 x 1 = 2
2 x 2 = 4
2 x 3 = 6
2 x 4 = 8
2 x 5 = 10
2 x 6 = 12
2 x 7 = 14
2 x 8 = 16
2 x 9 = 18
3 x 1 = 3
3 x 2 = 6
3 x 3 = 9
3 x 4 = 12
3 x 5 = 15
3 x 6 = 18
3 x 7 = 21
3 x 8 = 24
3 x 9 = 27
4 x 1 = 4
4 x 2 = 8
4 x 3 = 12
4 x 4 = 16
4 x 5 = 20
4 x 6 = 24
4 x 7 = 28
4 x 8 = 32
4 x 9 = 36
5 x 1 = 5
5 x 2 = 10
5 x 3 = 15
5 x 4 = 20
5 x 5 = 25
5 x 6 = 30
5 x 7 = 35
5 x 8 = 40
5 x 9 = 45
6 x 1 = 6
6 x 2 = 12
6 x 3 = 18
6 x 4 = 24
6 x 5 = 30
6 x 6 = 36
6 x 7 = 42
6 x 8 = 48
6 x 9 = 54
7 x 1 = 7
7 x 2 = 14
7 x 3 = 21
7 x 4 = 28
7 x 5 = 35
7 x 6 = 42
7 x 7 = 49
7 x 8 = 56
7 x 9 = 63
8 x 1 = 8
8 x 2 = 16
8 x 3 = 24
8 x 4 = 32
8 x 5 = 40
8 x 6 = 48
8 x 7 = 56
8 x 8 = 64
8 x 9 = 72
9 x 1 = 9
9 x 2 = 18
9 x 3 = 27
9 x 4 = 36
9 x 5 = 45
9 x 6 = 54
9 x 7 = 63
9 x 8 = 72
9 x 9 = 81

 

 

 

public class FlowEx19 {
	public static void main(String[] args) {
		for(int i=1; i<=3;i++)
			for(int j=1;j<=3;j++)
				for(int k=1;k<=3;k++)
					System.out.println(""+i+j+k);
	}
}
111
112
113
121
122
123
131
132
133
211
212
213
221
222
223
231
232
233
311
312
313
321
322
323
331
332
333

 

 

 

public class FlowEx20 {
	public static void main(String[] args) {
		for(int i=1;i<=5;i++) {
			for(int j=1;j<=5;j++) {
				System.out.printf("[%d,%d]",i,j);
			}
			System.out.println();
		}
	}
}
[1,1][1,2][1,3][1,4][1,5]
[2,1][2,2][2,3][2,4][2,5]
[3,1][3,2][3,3][3,4][3,5]
[4,1][4,2][4,3][4,4][4,5]
[5,1][5,2][5,3][5,4][5,5]

 

 

 

public class FlowEx21 {
	public static void main(String[] args) {
		for(int i=1;i<=5;i++) {
			for(int j=1;j<=5;j++) {
				if(i==j) {
					System.out.printf("[%d,%d]",i,j);
				}else {
					System.out.printf("%5c",' ');
				}
			}
			System.out.println();
		}
	}
}
[1,1]                    
     [2,2]               
          [3,3]          
               [4,4]     
                    [5,5]

 

 

 

public class FlowEx22 {
	public static void main(String[] args) {
		int[] arr = {10,20,30,40,50};
		int sum = 0;
		
		for(int i=0;i<arr.length;i++)
			System.out.printf("%d ", arr[i]);
		System.out.println();
		
		for(int tmp : arr) {
			System.out.printf("%d ", tmp);
			sum +=tmp;
		}
		System.out.println();System.out.println("sum="+sum);
	}
}
10 20 30 40 50 
10 20 30 40 50 
sum=150

 

 

public class FlowEx23 {
	public static void main(String[] args) {
		int i = 5;

		while (i-- != 0) {
			System.out.println(i + " - I can do it.");
		}
	}	//main의 끝
}
4 - I can do it.
3 - I can do it.
2 - I can do it.
1 - I can do it.
0 - I can do it.

 

 

 

public class FlowEx24 {
	public static void main(String[] args) {
		int i = 11;

		System.out.println("카운트 다운을 시작합니다.");

		while (i-- != 0) {
			System.out.println(i);

			for (int j = 0; j < 2_000_000_000; j++) {	//슬립함수로 변형
				;
			}
		}
		System.out.println("GAME OVER");
	}
}
카운트 다운을 시작합니다.
10
9
8
7
6
5
4
3
2
1
0
GAME OVER

 

 

 

public class FlowEx25 {
	public static void main(String[] args) {
		int num = 0, sum = 0;
		System.out.print("숫자를 입력하세요. (예:12345)>");

		Scanner scanner = new Scanner(System.in);
		String tmp = scanner.nextLine();// 화면을 통해 입력받은 내용을 tmp에 저장;
		num = Integer.parseInt(tmp); // 입력받은 문자열(tmp)을 숫자로 변환

		while (num != 0) {
			// num을 10으로 나눈 나머지를 sum에 더함
			sum += num % 10; // sum = sum + num%10;
			System.out.printf("sum=%3d num%d%n", sum, num);

			num /= 10; // num = num / 10; num을 10으로 나눈값을 다시 num에 저장
		}

		System.out.println("각 자리수의 합:" + sum);
		scanner.close();
	}
}
숫자를 입력하세요. (예:12345)>123
sum=  3 num123
sum=  5 num12
sum=  6 num1
각 자리수의 합:6

 

 

public class FlowEx26 {
	public static void main(String[] args) {
		int sum = 0;
		int i	= 0;
		
		// i를 1씩 증가시켜서 sum에 계속 더해나간다.
		while((sum += ++i) <= 100) {
			System.out.printf("%d - %d%n", i, sum);
		}
	}//main의 끝
}
1 - 1
2 - 3
3 - 6
4 - 10
5 - 15
6 - 21
7 - 28
8 - 36
9 - 45
10 - 55
11 - 66
12 - 78
13 - 91

 

 

 

public class FlowEx27 {
	public static void main(String[] args) {
		int num;
		int sum = 0;
		boolean flag = true;	// while문의 조건식으로 사용될 변수
		Scanner scanner = new Scanner(System.in);
		
		System.out.println("합계를 구할 숫자를 입력하세요. (끝내려면 0을 입력)");
		
		while(flag) {	// flag의 값이 true이므로 조건식은 참이 된다.
			System.out.println(">>");
			
			String tmp = scanner.nextLine();
			num = Integer.parseInt(tmp);
			
			if(num!=0) {
				sum += num;	// num이 0이 아니면, sum에 더한다.
			}else {
				flag = false;	// num이 0이면, flag의 값을 flase로 변경.
			}
		}	// while문의 끝
		System.out.println("합계:"+sum);
		scanner.close();
	}
}
합계를 구할 숫자를 입력하세요. (끝내려면 0을 입력)
>>
55
>>
33
>>
78
>>
0
합계:166

 

 

 

public class FlowEx28 {
	public static void main(String[] args) {
		int input = 0, answer = 0;

		answer = (int) (Math.random() * 100) + 1; // 1~100사이의 임의의 수를 저장
		Scanner scanner = new Scanner(System.in);

		do {
			System.out.print("1과 100사이의 정수를 입력하세요.>");
			input = scanner.nextInt();

			if (input > answer) {
				System.out.println("더 작은 수로 다시 시도해보세요.");
			} else if (input < answer) {
				System.out.println("더 큰 수로 다시 시도해보세요.");
			}
		} while (input != answer);

		System.out.println("정답입니다.");
		scanner.close();
	}
}
1100사이의 정수를 입력하세요.>50
더 큰 수로 다시 시도해보세요.
1100사이의 정수를 입력하세요.>75
더 큰 수로 다시 시도해보세요.
1100사이의 정수를 입력하세요.>87
더 큰 수로 다시 시도해보세요.
1100사이의 정수를 입력하세요.>93
더 작은 수로 다시 시도해보세요.
1100사이의 정수를 입력하세요.>90
정답입니다.

 

 

 

public class FlowEx29 {
	public static void main(String[] args) {
		for (int i = 1; i <= 100; i++) {
			System.out.printf("i=%d ", i);

			int tmp = i;

			do {
				// tmp%10이 3의 배수인지 확인(0 제외)
				if (tmp % 10 % 3 == 0 && tmp % 10 != 0)
					System.out.print("짝");
				// tmp /=10은 tmp = tmp / 10과 동일

			} while ((tmp /= 10) != 0);

			System.out.println();
		}
	}
}
i=1 
i=2 
i=3 짝
i=4 
i=5 
i=6 짝
i=7 
i=8 
i=9 짝
i=10 
i=11 
i=12 
i=13 짝
i=14 
i=15 
i=16 짝
i=17 
i=18 
i=19 짝
i=20 
i=21 
i=22 
i=23 짝
i=24 
i=25 
i=26 짝
i=27 
i=28 
i=29 짝
i=30 짝
i=31 짝
i=32 짝
i=33 짝짝
i=34 짝
i=35 짝
i=36 짝짝
i=37 짝
i=38 짝
i=39 짝짝
i=40 
i=41 
i=42 
i=43 짝
i=44 
i=45 
i=46 짝
i=47 
i=48 
i=49 짝
i=50 
i=51 
i=52 
i=53 짝
i=54 
i=55 
i=56 짝
i=57 
i=58 
i=59 짝
i=60 짝
i=61 짝
i=62 짝
i=63 짝짝
i=64 짝
i=65 짝
i=66 짝짝
i=67 짝
i=68 짝
i=69 짝짝
i=70 
i=71 
i=72 
i=73 짝
i=74 
i=75 
i=76 짝
i=77 
i=78 
i=79 짝
i=80 
i=81 
i=82 
i=83 짝
i=84 
i=85 
i=86 짝
i=87 
i=88 
i=89 짝
i=90 짝
i=91 짝
i=92 짝
i=93 짝짝
i=94 짝
i=95 짝
i=96 짝짝
i=97 짝
i=98 짝
i=99 짝짝
i=100

 

 

 

public class FlowEx30 {
	public static void main(String[] args) {
		int sum = 0;
		int i = 0;
		
		while(true) {
			if(sum > 100)
				break;
			++i;
			sum +=i;
		}// end of while
		
		System.out.println("i=" + i);
		System.out.println("sum=" + sum);
	}
}
i=14
sum=105

 

 

 

public class FlowEx31 {
	public static void main(String[] args) {
		for (int i = 0; i <= 10; i++) {
			if (i % 3 == 0)
				continue;
			System.out.println(i);
		}
	}
}
1
2
4
5
7
8
10

 

 

 

public class FlowEx32 {
	public static void main(String[] args) {
		int menu = 0;
//		int num = 0;

		Scanner scanner = new Scanner(System.in);

		while (true) {
			System.out.println("(1) square");
			System.out.println("(2) square root");
			System.out.println("(3) log");
			System.out.println("원하는 메뉴(1~3)를 선택하세요. (종료:0)>");

			String tmp = scanner.nextLine();// 화면에서 입력받은 내용을 tmp에 저장
			menu = Integer.parseInt(tmp);

			if (menu == 0) {
				System.out.println("프로그램을 종료합니다.");
				break;
			} else if (!(1 <= menu && menu <= 3)) {
				System.out.println("메뉴를 잘못 선택하셨습니다.(종료는 0)");
				continue;
			}

			System.out.println("선택하신 메뉴는 " + menu + "번입니다.");
		}
		scanner.close();
	}
}
(1) square
(2) square root
(3) log
원하는 메뉴(1~3)를 선택하세요. (종료:0)>
1
선택하신 메뉴는 1번입니다.
(1) square
(2) square root
(3) log
원하는 메뉴(1~3)를 선택하세요. (종료:0)>
0
프로그램을 종료합니다.

 

 

 

public class FlowEx33 {
	public static void main(String[] args) {
		// for문에 Loop1이라는 이름을 붙였다.
//		Loop1:
			for (int i = 2; i <= 9; i++) {
			for (int j = 1; j <= 9; j++) {
				if (j == 5)
//					break Loop1;
//				break;
//				continue Loop1;
				continue;
				System.out.println(i + "*" + j + "=" + i * j);
			} // end of for i
			System.out.println();
		} // end of Loop1
	}
}
2*1=2
2*2=4
2*3=6
2*4=8
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*6=18
3*7=21
3*8=24
3*9=27

4*1=4
4*2=8
4*3=12
4*4=16
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*6=30
5*7=35
5*8=40
5*9=45

6*1=6
6*2=12
6*3=18
6*4=24
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*6=42
7*7=49
7*8=56
7*9=63

8*1=8
8*2=16
8*3=24
8*4=32
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*6=54
9*7=63
9*8=72
9*9=81

 

 

 

import java.util.*;

public class FlowEx34 {
	public static void main(String[] args) {
		int menu = 0, num = 0;
		
		Scanner scanner = new Scanner(System.in);
		
		outer:
			while(true) {
				System.out.println("(1) square");
				System.out.println("(2) square root");
				System.out.println("(3) log");
				System.out.println("원하는 메뉴(1~3)를 선택하세요.(종료0)>");
				
				String tmp = scanner.nextLine();	// 화면에서 입력받은 내용을 tmp에 저장
				menu = Integer.parseInt(tmp);		// 입력받은 문자열(tmp)를 숫자로 변환
				
				if(menu==0) {
					System.out.println("프로그램을 종료합니다.");
					break;
				}else if (!(1<= menu && menu <=3)) {
					System.out.println("메뉴를 잘못 선택하셨습니다.(종료는0)");
					continue;
				}
				
				for(;;) {
					System.out.print("계산할 값을 입력하세요.(계산 종료:0, 전체 종료:99)>");
					tmp = scanner.nextLine();		// 화면에서 입력받은 내용을 tmp에 저장
					num = Integer.parseInt(tmp);	// 입력받은 문자열(tmp)를 숫자로 변환
					
					if(num==0)
						break;
					
					if(num==99)
						break outer;
					
					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의 끝
	}// main의 끝

}
(1) square
(2) square root
(3) log
원하는 메뉴(1~3)를 선택하세요.(종료0)>
1
계산할 값을 입력하세요.(계산 종료:0, 전체 종료:99)>25
result=625
계산할 값을 입력하세요.(계산 종료:0, 전체 종료:99)>0
(1) square
(2) square root
(3) log
원하는 메뉴(1~3)를 선택하세요.(종료0)>
2
계산할 값을 입력하세요.(계산 종료:0, 전체 종료:99)>25
result=5.0
계산할 값을 입력하세요.(계산 종료:0, 전체 종료:99)>0
(1) square
(2) square root
(3) log
원하는 메뉴(1~3)를 선택하세요.(종료0)>
3
계산할 값을 입력하세요.(계산 종료:0, 전체 종료:99)>100
result=4.605170185988092
계산할 값을 입력하세요.(계산 종료:0, 전체 종료:99)>99

 

 

3강의 예제를 모아둔 것이다.

일부는 다른 글에서 설명하면서 사용할 것이고 일부는 넘어갈 거라서 만약 코드 적기가 귀찮다면 복사 붙여넣기해서 사용하자.

ctrl + F 한 후 class이름을 검색하면 쉽게 찾을 수 있다.

public class OperatorEx01 {
	public static void main(String[] args) {

		int i = 5;
		i++; // i=i+1;
		System.out.println(i);

		i = 5;
		++i;
		System.out.println(i);

	}

}
6
6

 

 

public class OperatorEx02 {
	public static void main(String[] args) {
		int i = 5, j = 0;
		j = i++;
		System.out.println("j=i++; 실행 후, i=" + i + ", j=" + j);
		i = 5; 
		j = 0;
		j = ++i;
		System.out.println("j=++i; 실행 후, i=" + i + ", j=" + j);
	}
}
j=i++; 실행 후, i=6, j=5
j=++i; 실행 후, i=6, j=6

 

 

public class OperatorEx03 {
	public static void main(String[] args) {
		int i=5, j=5;
		System.out.println(i++);
		System.out.println(++j);
		System.out.println("i = " + i + ", j = " + j);		
		int x = 5;		
		x = x++ - ++x;
		System.out.println(x);		
		byte b = -128;
		b = (byte)-b;
		System.out.println(-b);
	}
}
5
6
i = 6, j = 6
-2
128

 

 

public class OperatorEx04 {
	public static void main(String[] args) {
		int i = -10;
		i = +i;
		System.out.println(i);

		i = -10;
		i = -i;
		System.out.println(i);
	}
}
-10
10

 

 

public class OperatorEx05 {
	public static void main(String[] args) {
		int a = 10;
		int b = 4;
        
		System.out.printf("%d + %d = %d%n", a, b, a + b);
		System.out.printf("%d - %d = %d%n", a, b, a - b);
		System.out.printf("%d * %d = %d%n", a, b, a * b);
		System.out.printf("%d / %d = %d%n", a, b, a / b);
		System.out.printf("%d / %f = %f%n", a, (float) b, a / (float) b);
	}
}
10 + 4 = 14
10 - 4 = 6
10 * 4 = 40
10 / 4 = 2
10 / 4.000000 = 2.500000
66.66666666666667
66.67
66.66
66.66200

 

 

public class Exercise3_06 {
	public static void main(String[] args) {
		byte a = 10;
		byte b = 20;
		byte c = a + b;
		System.out.println(c);
	}
}
30

 

 

public class Exercise3_07 {
	public static void main(String[] args) {
		byte a = 10;
		byte b = 20;
		byte c = (byte) (a + b);
		System.out.println(c);
	}
}
44

 

 

public class OperatorEx08 {
	public static void main(String[] args) {
		int a = 1_000_000;	// 1,000,000 1백만
		int b = 2_000_000;  // 2,000,000 2백만
		
//		int c = a * b; // 2 * 10^12
		long c = a* b;	// a* b = 2,000,000,000,000 ?
		System.out.println(c);
	}

}
-1454759936

 

public class OperatorEx09 {
	public static void main(String[] args) {
		long a = 1_000_000 * 1_000_000;
		long b = 1_000_000 * 1_000_000L;
		
		System.out.println("a="+a);
		System.out.println("b="+b);
	}

}
a=-727379968
b=1000000000000

 

 

public class OperatorEx10 {
	public static void main(String[] args) {
		int a = 1000_000;

		int result1 = a * a / a;
		int result2 = a / a * a;
		
		System.out.printf("%d * %d / %d = %d%n", a, a, a, result1);
		System.out.printf("%d / %d * %d = %d%n", a, a, a, result2);

	}
}
1000000 * 1000000 / 1000000 = -727
1000000 / 1000000 * 1000000 = 1000000

 

 

public class OperatorEx11 {
	public static void main(String[] args) {
		char a = 'a';
		char d = 'd';
		char zero = '0';
		char two = '2';
		
		System.out.printf("'%c' - '%c' = %d%n", d, a, d - a);
		System.out.printf("'%c' - '%c' = %d%n", two, zero, two - zero);
		System.out.printf("'%c' = %d%n", a, (int)a);
		System.out.printf("'%c' = %d%n", d, (int)d);
		System.out.printf("'%c' = %d%n", zero, (int)zero);
		System.out.printf("'%c' = %d%n", two, (int)two);
		
//		char c1 = 'A';
//		char c2 = c1 + 1; // 변수와 리터럴의 연산이라 안됨 final로 리터럴로바꾸면 ㄱ나ㅡㅇ
//		상수 포함
		char c2 = 'a' + 1; // 리터럴 간의 연산
		
		char c3 = 0xAC00;
		System.out.println(c2);
		System.out.println(c3);
		
		int sec = 60 * 60 * 24; // 
		System.out.println(sec);
	}

}
'd' - 'a' = 3
'2' - '0' = 2
'a' = 97
'd' = 100
'0' = 48
'2' = 50
b
가
86400

 

 

public class OperatorEx12 {
	public static void main(String[] args) {
		
		char c1 = 'a';	// c1에는 문자 'a'의 코드값인 97이 저장된다.
		char c2 = c1;	// c1에 저장되어 있는 값이 c2에 저장된다.
		char c3 = ' ';	// c3를 공백으로 초기화 한다.
		
		int i = c1 + 1;	// 'a'+1 > 97+1 > 98
		
		c3 = (char)(c1 + 1);	// c1 + 1의 형태가 int 이므로 char로 변환
		c2++;
		c2++;
		
		System.out.println("i=" + i);
		System.out.println("c2=" + c2);
		System.out.println("c3=" + c3);
	}

}
i=98
c2=c
c3=b

 

 

public class OperatorEx13 {
	public static void main(String[] args) {
		char c1 = 'a';
		
//		char c2 = c1 + 1; // 컴파일 에러
		char c2 = 'a' + 1;	//리터럴간의 연산이므로 에러 X
		
		System.out.println(c1);
		System.out.println(c2);
	}

}
a
b

 

 

public class OperatorEx14 {
	public static void main(String[] args) {
		char c = 'a';
		for (int i = 0; i < 26; i++) {
			// 블럭{} 안의 문장을 26번 반복한다.]
			System.out.print(c++);
		} // 'a;부터 26개의 문자를 출력한다.

		System.out.println(); // 줄바꿈을한다

		c = 'A';
		for (int i = 0; i < 26; i++) { // 블럭 {} 안의 문장을 26번 반복한다.
			System.out.print(c++);	   //'A'부터 26개의 문자를 출력한다.
		}

		System.out.println();

		c = '0';
		for (int i = 0; i < 10; i++)	// 블럭{} 안의 문장을 10번 반복한다.
			System.out.println(c++);	// '0'부터 10개의 문자를 출력한다.
		System.out.println();

		// 줄바꿈을한다
	}
}
abcdefghijklmnopqrstuvwxyz
ABCDEFGHIJKLMNOPQRSTUVWXYZ
0
1
2
3
4
5
6
7
8
9

 

 

import java.util.Scanner;

public class OperatorEx15 {
	public static void main(String[] args) {
		Scanner scanner = new Scanner(System.in);
		char lowerCase = 'x';
		char upperCase = (char)(lowerCase - 32);
		System.out.println(upperCase);
		}
 }
X

 

 

public class OperatorEx16 {
	public static void main(String[] args) {
		float pi = 3.141592f;
		float shortPi = (int)(pi * 1000) / 1000f;
		System.out.println(shortPi);
	}

}
3.141

 

 

public class OperatorEx17 {
	public static void main(String[] args) {
		double pi = 3.141592;
		double shortPi = (int)(pi * 1000 + 0.5) / 1000.0;

		System.out.println(shortPi);
	}

}
3.142

 

 

public class OperatorEx18 {
	public static void main(String[] args) {
		double pi = 3.141592;
		double shortPi = Math.round(pi * 1000) / 1000.0;
		System.out.println(shortPi);
	}

}
3.142

 

 

public class OperatorEx19 {
	public static void main(String[] args) {
		int x = 10;
		int y = 8;
		
		System.out.printf("%d을 %d로 나누면, %n", x, y);
		System.out.printf("몫은 %d이고, 나머지는 %d입니다.%n", x / y, x % y);
        	}

}
108로 나누면, 
몫은 1이고, 나머지는 2입니다.

 

 

public class OperatorEx20 {
	public static void main(String[] args) {
		System.out.println(-10%8);
		System.out.println(10%-8);	
		System.out.println(-10%-8);		
	}

}
-2
2
-2

 

 

public class OperatorEx21 {
	public static void main(String[] args) {
		System.out.printf("10 == 10.0f \t %b%n", 10==10.0f);
		System.out.printf("'0' == 0 \t %b%n", '0' == 0);	
		System.out.printf("'A' == 65 \t %b%n", 'A' == 65);
		System.out.printf("'A' > 'B' \t %b%n", 'A' > 'B');	 
		System.out.printf("'A'+1 != 'B' \t %b%n", 'A'+1 != 'B');	
	}
}
10 == 10.0f 	 true
'0' == 0 	 false
'A' == 65 	 true
'A' > 'B' 	 false
'A'+1 != 'B' 	 false

 

 

public class OperatorEX22 {
	public static void main(String[] args) {
		float f = 0.1f;
		double d = 0.1;
		double d2 = (double) f;

		System.out.printf("10.0==10.0f	%b%n ", 10.0 == 10.0f);
		System.out.printf("0.1==0.1f	%b%n ", 0.1 == 0.1f);
		System.out.printf("f=%19.17f%n ", f);
		System.out.printf("d =%19.17f%n ", d);
		System.out.printf("d2=%19.17f%n ", d2);
		System.out.printf("d==f %b%n ", d == f);
		System.out.printf("d==d2 %b%n ", d == d2);
		System.out.printf("d2==f %b%n ", d2 == f);
		System.out.printf("(float)d==f %b%n ", (float) d == f);
	}

}
0.1==0.1f	false
 f=0.10000000149011612
 d =0.10000000000000000
 d2=0.10000000149011612
 d==f false
 d==d2 false
 d2==f true
 (float)d==f true

 

 

public class OperatorEx23 {
	public static void main(String[] args) {
		String str1 = "abc";
		String str2 = new String("abc");

		System.out.printf("\"abc\"==\"abc\" ? %b%n", "abc"=="abc");
		System.out.printf(" str1==\"abc\" ? %b%n", str1=="abc");
		System.out.printf("str1.equals(\"abc\") ? %b%n", str1.equals("abc"));
		System.out.printf("str2.equals(\"abc\") ? %b%n", str2.equals("abc"));
		System.out.printf("str2.equalsIgnotreCase(\"abc\") ? %b%n", str2.equalsIgnoreCase("abc"));
	}

}
"abc"=="abc" ? true
 str1=="abc" ? true
 str1=="abc" ? false
str1.equals("abc") ? true
str2.equals("abc") ? true
str2.equalsIgnotreCase("abc") ? true

 

 

public class OperatorEx24 {
	public static void main(String[] args) {
		int x = 0;
		char ch = ' ';
		
		x = 15;
		System.out.printf("x=%2d, 10 < x && x < 20 = %b%n", x, 10 < x && x < 20);
		
		x = 6;
		System.out.printf("x=%2d , x%%2==0 || x%%3==0 && x%%6!=0 = %b%n",x, x%2==0 || x%3==0&&x%6!=0);
		System.out.printf("x=%2d , (x%%2==0 || x%%3==0) && x%%6!=0 = %b%n",x, (x%2==0 || x%3==0)&&x%6!=0);
		
		ch='1';
		System.out.printf("ch='%c', '0' <= ch && ch <= '9' =%b%n", ch, '0' <= ch && ch <='9');
		
		ch='a';
		System.out.printf("ch='%c', 'a' <= ch && ch <= 'z' =%b%n", ch, 'a' <= ch && ch <='z');
		
		ch='A';
		System.out.printf("ch='%c', 'A' <= ch && ch <= 'Z' =%b%n", ch, 'A' <= ch && ch <='Z');
		

		ch='q';
		System.out.printf("ch='%c', 'q' <= ch && ch <= 'Q' =%b%n", ch, 'q' <= ch && ch <='Q');
	}

}
x=15, 10 < x && x < 20 = true
x= 6 , x%2==0 || x%3==0 && x%6!=0 = true
x= 6 , (x%2==0 || x%3==0) && x%6!=0 = false
ch='1', '0' <= ch && ch <= '9' =true
ch='a', 'a' <= ch && ch <= 'z' =true
ch='A', 'A' <= ch && ch <= 'Z' =true
ch='q', 'q' <= ch && ch <= 'Q' =false

 

 

import java.util.Scanner;

public class OperatorEx25 {

	public static void main(String[] args) {
		Scanner scanner = new Scanner(System.in);
		char ch = ' ';
		for (int i = 1; i <= 10; i--) {

			System.out.printf("문자를 하나 입력하세요.>");

			String input = scanner.nextLine();
			ch = input.charAt(0);

			if ('0' <= ch && ch <= '9') {
				System.out.printf("입력하신 문자는 숫자입니다.%n");
			}
			if (('a' <= ch && ch <= 'z') || ('A' <= ch && ch <= 'z')) {
				System.out.printf("입력하신 문자는 영문자입니다.%n");
			}	
		} // main
		scanner.close();}
문자를 하나 입력하세요.>a
입력하신 문자는 영문자입니다.
문자를 하나 입력하세요.>1
입력하신 문자는 숫자입니다.
문자를 하나 입력하세요.>

 

 

public class OperatorEx26 {
	public static void main(String[] args) {
		int a = 5;
		int b = 0;

		System.out.printf("a=%d, b=%d%n", a, b);
		System.out.printf("a!=0 || ++b!=0 = %b%n", a != 0 || ++b != 0);
		System.out.printf("a=%d, b=%d%n", a, b);
		System.out.printf("a==0 && ++b!=0 = %b%n", a == 0 && ++b != 0);
		System.out.printf("a=%d, b=%d%n", a, b);
	}
}
a=5, b=0
a!=0 || ++b!=0 = true
a=5, b=0
a==0 && ++b!=0 = false
a=5, b=0

 

 

public class OperatorEx27 {
	public static void main(String[] args) {
		boolean b = true;
		char ch = 'c';

		System.out.printf("b=%b%n", b);
		System.out.printf("!b=%b%n", !b);
		System.out.printf("!!b=%b%n", !!b);
		System.out.printf("!!!b=%b%n", !!!b);
		System.out.println();

		System.out.printf("ch=%c%n", ch);
		System.out.printf("ch < 'a' || ch > 'z'=%b%n", ch < 'a' || ch > 'z');

		System.out.printf("!('a'<=ch && ch<='z'=%b%n", !('a' <= ch && ch <= 'z'));

		System.out.printf("'a'<=ch && ch<='z' =%b%n", 'a' <= ch && ch <= 'z');
		} // main의 끝
}
b=true
!b=false
!!b=true
!!!b=false

ch=c
ch < 'a' || ch > 'z'=false
!('a'<=ch && ch<='z'=false
'a'<=ch && ch<='z' =true
4
7
3
-2
24
1
11111111111111111111111111111010
11111111111111111111111111111101
1111111111111111111111111111101
2147483645
5
5

 

 

public class OperatorEx28 {
	public static void main(String[] args) {
		int x = 0xAB, y = 0xF;

		System.out.printf("x = %#X  \t\t%s%n", x, toBinaryString(x));
		System.out.printf("y = %#X  \t\t%s%n", y, toBinaryString(y));
		System.out.printf("%#X | %#X = %#X \t%s%n", x, y, x | y, toBinaryString(x | y));
		System.out.printf("%#X & %#X = %#X \t%s%n", x, y, x & y, toBinaryString(x & y));
		System.out.printf("%#X ^ %#X = %#X \t%s%n", x, y, x ^ y, toBinaryString(x ^ y));
		System.out.printf("%#X ^ %#X ^ %#X = %#X \t%s%n", x, y, y, x ^ y, toBinaryString(x ^ y ^ y));

	} // main의 끝

	static String toBinaryString(int x) { // 10진 정수를 2진수로 변환하는 메서드
		String zero = "00000000000000000000000000000000";
		String tmp = zero + Integer.toBinaryString(x);
		return tmp.substring(tmp.length() - 32);
	}
}
x = 0XAB  		00000000000000000000000010101011
y = 0XF  		00000000000000000000000000001111
0XAB | 0XF = 0XAF 	00000000000000000000000010101111
0XAB & 0XF = 0XB 	00000000000000000000000000001011
0XAB ^ 0XF = 0XA4 	00000000000000000000000010100100
0XAB ^ 0XF ^ 0XF = 0XA4 	00000000000000000000000010101011

 

 

public class OperatorEx29 {
	public static void main(String[] args) {
		byte p = 10;
		byte n = -10;

		System.out.printf(" p =%d |t%s%n", p, toBinaryString(p));
		System.out.printf("~p =%d |t%s%n", ~p, toBinaryString(~p));
		System.out.printf("~p+1 =%d |t%s%n", ~p+1, toBinaryString(~p+1));
		System.out.printf("~~p =%d |t%s%n", ~~p, toBinaryString(~~p));
		System.out.println();
		System.out.printf(" n =%d%n", n);
		System.out.printf("~(n-1)=%d%n", ~(n-1));
	} // main의 끝

	static String toBinaryString(int x) { // 10진 정수를 2진수로 변환하는 메서드
		String zero = "00000000000000000000000000000000";
		String tmp = zero + Integer.toBinaryString(x);
		return tmp.substring(tmp.length() - 32);
	}
}
 p =10 |t00000000000000000000000000001010
~p =-11 |t11111111111111111111111111110101
~p+1 =-10 |t11111111111111111111111111110110
~~p =10 |t00000000000000000000000000001010

 n =-10
~(n-1)=10

 

 

public class OperatorEx30 {
	// 10진 정수를 2진수로 변환하는 메서드
	static String toBinaryString(int x) { 
		String zero = "00000000000000000000000000000000";
		String tmp = zero + Integer.toBinaryString(x);
		return tmp.substring(tmp.length() - 32);
	}
	public static void main(String[] args) {
		
		int dec = 8;
		System.out.printf("%d >> %d = %4d |t%s%n", dec, 0, dec >> 0, toBinaryString(dec >> 0));
		System.out.printf("%d >> %d = %4d |t%s%n", dec, 1, dec >> 1, toBinaryString(dec >> 1));
		System.out.printf("%d >> %d = %4d |t%s%n", dec, 2, dec >> 2, toBinaryString(dec >> 2));
		System.out.printf("%d << %d = %4d |t%s%n", dec, 0, dec << 0, toBinaryString(dec << 0));
		System.out.printf("%d << %d = %4d |t%s%n", dec, 1, dec << 1, toBinaryString(dec << 1));
		System.out.printf("%d << %d = %4d |t%s%n", dec, 2, dec << 2, toBinaryString(dec << 2));
		System.out.println();
		
		dec = -8;
		System.out.printf("%d >> %d = %4d |t%s%n", dec, 0, dec >> 0, toBinaryString(dec >> 0));
		System.out.printf("%d >> %d = %4d |t%s%n", dec, 1, dec >> 1, toBinaryString(dec >> 1));
		System.out.printf("%d >> %d = %4d |t%s%n", dec, 2, dec >> 2, toBinaryString(dec >> 2));
		System.out.printf("%d << %d = %4d |t%s%n", dec, 0, dec << 0, toBinaryString(dec << 0));
		System.out.printf("%d << %d = %4d |t%s%n", dec, 1, dec << 1, toBinaryString(dec << 1));
		System.out.printf("%d << %d = %4d |t%s%n", dec, 2, dec << 2, toBinaryString(dec << 2));
		System.out.println();
		
		dec = 8;
		System.out.printf("%d >> %2d = %4d |t%s%n", dec, 0, dec >> 0, toBinaryString(dec >> 0));
		System.out.printf("%d >> %2d = %4d |t%s%n", dec, 32, dec >> 32, toBinaryString(dec >> 32));
		
	} // main의 끝
}
8 >> 0 =    8 |t00000000000000000000000000001000
8 >> 1 =    4 |t00000000000000000000000000000100
8 >> 2 =    2 |t00000000000000000000000000000010
8 << 0 =    8 |t00000000000000000000000000001000
8 << 1 =   16 |t00000000000000000000000000010000
8 << 2 =   32 |t00000000000000000000000000100000

-8 >> 0 =   -8 |t11111111111111111111111111111000
-8 >> 1 =   -4 |t11111111111111111111111111111100
-8 >> 2 =   -2 |t11111111111111111111111111111110
-8 << 0 =   -8 |t11111111111111111111111111111000
-8 << 1 =  -16 |t11111111111111111111111111110000
-8 << 2 =  -32 |t11111111111111111111111111100000

8 >>  0 =    8 |t00000000000000000000000000001000
8 >> 32 =    8 |t00000000000000000000000000001000

 

 

public class OperatorEx31 {
	public static void main(String[] args) {
		int dec =1234;
		int hex = 0xABCD;
		int mask = 0xF;
		
		System.out.printf("hex=%X%n", hex);
		System.out.printf("%X%n", hex & mask);
		
		hex = hex >> 4;
		System.out.printf("%X%n", hex & mask);
		
		hex = hex >> 4;
		System.out.printf("%X%n", hex & mask);
		
		hex = hex >> 4;
		System.out.printf("%X%n", hex & mask);
	}

}
hex=ABCD
D
C
B
A

 

 

public class OperatorEx32 {
	public static void main(String[] args) {
		int x, y, z;
		int absX, absY, absZ;
		char signX, signY, signZ;
		
		x = 10;
		y = -5;
		z = 0;
		
		absX = x >= 0 ? x : -x; // x의 값이 음수이면, 양수로 만든다.
		absY = y >= 0 ? y : -y;
		absZ = z >= 0 ? z : -z;
		
		signX = x > 0 ? '+' : (x==0 ? ' ' : '-'); //조건 연산자를 중첩
		signY = y > 0 ? '+' : (y==0 ? ' ' : '-');
		signZ = z > 0 ? '+' : (z==0 ? ' ' : '-'); 
		
		System.out.printf("x=%c%d%n", signX, absX);
		System.out.printf("y=%c%d%n", signY, absY);
		System.out.printf("z=%c%d%n", signZ, absZ);
		
	}

}
x=+10
y=-5
z= 0

 

+ Recent posts