더보기
package control;

public class Q4_1 {

	public static void main(String[] args) {
		int x = 10;
		char ch = ' ';
		int year = 430;
		boolean powerOn = false;
		String str = "yes";
		
		//1번
		if(x > 10 && x <20) {
			
		}
		
		//2번
		if(ch != ' ' || ch != '\t') {
			
		}
		
		//3번
		if(ch == 'X' || ch == 'x') {
			
		}
		
		//4번
		if(ch >= '0' && ch <= '9') {
			
		}
		
		//5번
		if((ch >= 'A' && ch <= 'Z')||(ch >= 'a' && ch <='z')) {
			
		}
		
		//6번
		if((year%400==0||year%4==0)&&(year%100!=0)) {
			
		}
		
		//7번
		if(!powerOn) { //= if(powerOn!=true)
			
		}
		
		//8번
		if(str.equals("yes")) {
			
		}
		
	}

}

 

더보기

73

 

package control;

public class Q4_2 {

public static void main(String[] args) {
int sum = 0;
for(int i = 1; i <= 20; i++) {
if(i % 2 != 0 && i %3 != 0) {
sum += i;
}
}
System.out.println("sum : "+sum);
}

}

 

더보기

220

 

package control;

public class Q4_3 {

	public static void main(String[] args) {
		int sum = 0;
		for(int i = 1; i<=10; i++) {
			for(int j = 1; j<=i; j++) {
				sum += j;
			}
		}
		System.out.println("sum : "+sum);
	}

}

 

더보기

199

 

package control;

public class Q4_4 {

	public static void main(String[] args) {
		int num = 0; 
		int sum = 0; //총합
		int s = 1; //값의 부호를 바꿔주는 변수
		
		for(int i = 1; ; i++, s=-s) {
			num = i * s;
			sum += num;
			
			if(sum >= 100) break;
		}
		System.out.println("num : "+num);
		System.out.println("sum : "+sum);
	}

}

 

더보기
package control;

public class Q4_5 {

	public static void main(String[] args) {
		int i = 0;
		while(i <= 10) {
			int j = 0;
			while(j <=i) {
				System.out.print("*");
				j++;
			}
			System.out.println();
			i++;
		}
	}

}

 

더보기

>> 실행결과

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

package control;

public class Q4_6 {

	public static void main(String[] args) {
		//주사위 2개 - 6x6 = 36가지
		for(int i = 1; i <= 6; i++) {
			for(int j = 1; j <= 6; j++) {
				if(i+j==6) {
					System.out.printf("[%d, %d]\n",i,j);
				}
			}
		}
	}

}

 

 

더보기
package control;

public class Q4_7 {

	public static void main(String[] args) {
		int value = (int)(Math.random()*6)+1;
		System.out.println("value:"+value);
	}

}

 

더보기
package control;

public class Q4_8 {

	public static void main(String[] args) {
		for(int x = 0; x < 11; x++) {
			for(int y = 0; y < 11; y++) {
				if(2*x+4*y==10) {
					System.out.printf("x=%d, y=%d\n",x,y);
				}
			}
		}
	}

}

 

더보기

int tmp = str.charAt(i)-'0';
sum += tmp;

 

 

더보기
int tmp = num;
		
while(tmp>0) {
    sum += tmp%10;
    tmp = tmp/10;
}

 

더보기
package control;

public class Q4_11 {

	public static void main(String[] args) {
		int num1 = 1;
		int num2 = 1;
		int num3 = 0;
		
		System.out.print(num1+","+num2);
		
		for(int i = 0; i < 8; i++) {
			num3 = num1 + num2;
			System.out.print(","+num3);
			num1 = num2;
			num2 = num3;
		}
	}

}

 

 

더보기
package control;

public class Q4_13 {

	public static void main(String[] args) {
		String value = "12o34";
		char ch = ' ';
		boolean isNumber = true;
		
		for(int i = 0; i < value.length(); i++) {
			ch = value.charAt(i);
			if(!(ch >= '0' && ch <= '9')) {
				isNumber = false;
				break;
			}
		}
		
		if(isNumber) {
			System.out.println(value+"는 숫자입니다.");
		}else {
			System.out.println(value+"는 숫자가 아닙니다.");
		}
	}

}

 

더보기
package control;

public class Q4_14 {

	public static void main(String[] args) {
		int answer = (int)(Math.random()*100)+1; //1~100사이 컴터숫자
		int input = 0; //사용자 입력숫자
		int count = 0; //시도횟수
		
		java.util.Scanner s = new java.util.Scanner(System.in);
		
		do {
			count++;
			System.out.print("1과 100사이의 값을 입력하세요 : ");
			input = s.nextInt();
			
			if(input == answer) {
				System.out.println("맞췄습니다.");
			}else if(input > answer) {
				System.out.println("더 작은 수를 입력하세요.");
			}else{
				System.out.println("더 큰 수를 입력하세요.");
			}
			
			if(count >= 6) {
				System.out.println("시도횟수는 6번입니다.");
				break;
			}
		}while(true);
		
		s.close();
	}

}

 

더보기
package control;

public class Q4_15 {

	public static void main(String[] args) {
		int number = 12321;
		int tmp = number;
		
		int result = 0; //변수 number를 거꾸로 변환해서 담을 변수
		
		while(tmp != 0) {
			result = result*10+tmp%10;
			tmp = tmp/10;
		}
		
		if(number == result)
			System.out.println(number + "는 회문수 입니다.");
		else 
			System.out.println(number + "는 회문수가 아닙니다.");
	}

}

 

■ 배치관리자(LayoutManager)

- 레이아웃의 조상 인터페이스이다.

 

■ 레이아웃이란?

- 레이아웃은 컴포넌트들을 배치하는 방식을 말하는 것으로,

  이 방식에 따라 컨테이너 안에 추가되는 컴포넌트의 위치와 크기를 자동적으로 결정한다.

- 레이아웃 곧, 배치 방식도 하나의 객체이므로, 객체 생성 후 사용이 가능하다.

  (단, 컨테이너처럼 디폴트로 가진 레이아웃 방식이 있는 경우 반드시 레이아웃 객체를 생성할 필요가 없다)

 

■ 레이아웃의 종류

배치방식 특징
BorderLayout 컴포넌트를 동서남북, 중간에 배치할 수 있다.
*JFrame,JApplet,JDialog의 디폴트 배치관리자
FlowLayout 컴포넌트를 최상단에서 좌->우로 배치한다.
*JPanel, Applet의 디폴트 배치관리자
GridLayout 컴포넌트를 바둑판 형식으로 배치(행과 열)
*행을 기준으로 열의 갯수가 자동 지정
CardLayout 여러 장의 카드를 겹쳐놓은 형태
BoxLayout (생략)

 

더보기

참조 -- 

아래 내용부터는 https://movefast.tistory.com/46 내용을 일부 수정, 요약하였다.

■ BorderLayout

- 최상위 컨테이너 JFrame, JApplet, JDialog는 BorderLayout방식을 따른다.

  만약, 컨테이너 내에 컴포넌트 객체를 추가할 경우, 아래와 같이 컴포넌트가 배치될 영역을 지정한다.

   add(객체명, "East"); 또는 add(객체명, BorderLayout.EAST);

- 컴포넌트가 배치될 영역을 지정하지 않으면 자동으로 Center로 배치된다.

- 같은 위치에 컴포넌트를 추가하면 뒤 컴포넌트가 앞 컴포넌트를 가릴 수 있다.

생성자/메소드 설명
BorderLayout()  
BorderLayout(int hgap, int vgap) hgap : horizonal gap, vgap : vertical gap
수평, 수직 간격을 생성과 동시에 지정
setHgap(int hgap) : void 수평 간격 지정
setVgap(int vgap) : void 수직 간격 지정

 

■ FlowLayout

- JPanel의 디폴트 배치관리자.

- 너비를 벗어날 경우 다음 줄에서 다시 배치 시작

생성자 설명
FlowLayout() 기본 설정 : 중앙배치, 수평 수직 5px간의 간격
FlowLayout(int align) align = 정렬 방식
FlowLayout.LEADING, FlowLayout.CENTER, FlowLayout.TRAILING
FlowLayout(int align, int vgap, int hgap) 정렬방식, 수평간격, 수직간격 설정

 

■ GridLayout

- 행과 열의 바둑판 형식으로 컴포넌트 배치 

- 모든 컴포넌트의 크기는 같으며, 모든 공간을 컴포넌트로 채운다.

- 행을 기준으로 격자를 맞추는 것이 원칙이다.

- 윈도우의 크기를 변경하면 그 크기에 맞추어 컴포넌트의 크기가 자동 변경된다.

생성자 설명
GridLayout(int rows, int cols) 기본 설정 : 컴포넌트 수에 맞춰 자동 설정됨
수동 설정 : 행, 열 갯수 입력
GridLayout(int rows, int cols, int hgap, int vgap) 행, 열, 수평간격, 수직간격

 

■ CardLayout

- 여러 장의 컨테이너 객체(카드)를 겹겹이 겹쳐 놓은 형태

- 하나의 컨테이너의 배치 방식을 CardLayout로 하고, 그 안에 다수의 컨테이너를 묶는다.

생성자/메소드 설명
CardLayout()  
CardLayout(int hgap, int vgap) 수평 수직간격 설정
previous(Container parent) : void 
이전 순서의 컨테이너 show
next(Container parent) : void 
다음 순서의 컨테이너 show
first(Container parent) : void  첫번째 순서의 컨테이너 show
last(Container parent) : void 
마지막 순서의 컨테이너 show
show(Container parent, String s) : void 
특정 이름(문자열)의 컨테이너 show

 

 

 

[참조]

- 블로그 https://movefast.tistory.com/46

- 오라클 https://docs.oracle.com/javase/7/docs/api/java/awt/LayoutManager.html

■ JFrame 컨테이너

- Container 상속 : 컴포넌트를 추가(add)/지우기(remove), 컨테이너 내 배치방식(Layout) 설정

- JFrame 기능 : 컨테이너의 타이틀, 사이즈, 위치 등을 설정 가능 

- JFrame은 기본적으로 Border Layout방식을 따른다. **이 부분은 별도 포스팅 예정이며 여기서는 불필요한 내용이다.

메소드 정리

■ 그림으로 표현한 JFrame

 

■ 코드화

   [유의할 점]
   - DefaultCloseOperation설정을 하지 않으면 [x]를 누를 때 숨김처리(Not Visible)된다.
      * [x] 선택 시, 프로그램을 종료하려면 EXIT_ON_CLOSE 해주기
package window;

import javax.swing.JFrame;

class BasicJFrame extends JFrame{
	BasicJFrame(){
		
		this.setTitle("Basic JFrame");
		//또는 super("Title"); 로 타이틀 지정 가능하다.
		
		this.setLocation(200,200);
		
		this.setSize(400,400);
		
		this.setVisible(true);
		
		this.setDefaultCloseOperation(EXIT_ON_CLOSE);
	}
}

public class JFrameTest{
	public static void main(String[] args) {
		new BasicJFrame();
	}
}

>> 결과

1. GUI란?

- GUI는 사용자가 컴퓨터와 눈에 보이는(Graphic) 상호작용(interface)을 할 수 있게 한 것
- GUI의 종류 : AWT패키지, Swing패키지

AWT(Abstract Windowing Toolkit)
- AWT은 중량 컴포넌트(heavy weight)이며, 운영체제의 자원을 사용한다. 운영체제에 부담되나 속도 빠르다.

Swing
- Swing은 AWT를 확장한 경량 컴포넌트(Light weight)이며, 다양한 플랫폼에도 사용할 수 있게 했다.

 

2. GUI의 전체 구조도

- 이미지 참조 링크 : https://myeonguni.tistory.com/1006

참조 : 명우니 닷컴

 

3. 컴포넌트란?

- 윈도우창에 들어가는 모든 독립적인 단위모듈컴포넌트라고 한다.
- 이 중에서 다른 컴포넌트를 하나로 묶어주는 컴포넌트를 컨테이너라 한다.
- 컨테이너 컴포넌트의 조상은 AWT패키지의 Cotainer이다.
- 컨테이너 외의 컴포넌트들의 조상은 Swing패키지 내에서 JComponent이다.

3-1) Container와 JComponent의 주요 메소드

(AWT) Container

관련 메소드
컴포넌트 getter
컴포넌트 추가
getComponent() : Component
add(Component comp) : Component
add(String name, Component comp) : Component
add(Component comp, int index) : Component
add(Component comp, Object constraints) : void
add(Component comp, Object constraints, int index) : void
컴포넌트 제거 remove(int index) : void
remove(Component comp) : void
removeAll() : void
레이아웃(배치방식) 설정 setLayout(LayoutManager mgr) : void

 

(Swing) JComponent

- 참조 : https://m.blog.naver.com/rain483/220735906752

관련 메소드 설명
모양 void setForeground(Color)
void setBackground(Color)
void setOpaque(boolean)
void setFont(Font)
Font getFont()
전경색 설정
배경색 설정
불투명성 설정
폰트 설정
폰트 리턴
위치와 크기 int getWidth()
int getHeight()
int getX()
int getY()
Point getLocationOnScreen
void setLocation(int, int)
void setSize
폭 리턴
높이 리턴
x좌표 리턴
y좌표 리턴
스크린 좌표상에서의 컴포넌트 좌표
위치 지정
크기 지정
상태 void setEnable(boolean)
void setVisible(boolean)
boolean isVisible()
컴포넌트 활성화/비활성화
컴포넌트 보이기/숨기기
컴포넌트의 보이는 상태 리턴
컨테이너 Container getParent()
Contaienr getTopLevelAncestor()
부모 컨테이너 리턴
최상위 부모 컨테이너 리턴

 

3-2) Swing 컨테이너

- 컨테이너는 가벼운 컴포넌트들을 하나로 묶기 위해 사용된다.

종류 이름 내용 default 배치방식
최상위
컨테이너
JFrame 윈도우창 BoderLayout
JApplet 브라우저 내에서 작동하는 윈도우창 BoderLayout
JDiaglog 일종의 메세지창/
알럿과 같은 대화상자 형식의 애플리케이션에 적합
BoderLayout
JWindow (생략) (생략)
일반 JPanel 컴포넌트를 패널형식으로 묶음 FlowLayout

 

3-3) 가장 많이 사용되는 13가지 컴포넌트

- 코드 설명 번역 ) 가장 많이 사용하는 13가지 컴포넌트 https://www.educba.com/swing-components-in-java/

이름 그림/설명 코드
ImageIcon (생략) ImageIcon homeIcon = new ImageIcon(“src/images/home.jpg”);
JButton

<생성자의 인자>
- 문자열 또는 이미지
- 이미지+문자열도 가능
JButton okBtn = new JButton(“Ok”);

JButton homeBtn = new JButton(homeIcon);

JButton btn2 = new JButton(homeIcon, “Home”);
JLabel checkbox, button등에 붙는 라벨
*독자적으로 사용 가능
JLabel textLbl = new JLabel(“This is a text label.”);

JLabel imgLabel = new JLabel(homeIcon);
JComboBox

<생성자의 인자>
- 문자열 배열
String[] cityStrings = { "Mumbai", "London", "New York", "Sydney", "Tokyo" };
JComboBox cities = new JComboBox(cityList);
cities.setSelectedIndex(3);
JCheckBox

<생성자의 인자>
- 옆에 붙는 라벨 문자열
- default체크값(on= true)
CheckBox chkBox = new JCheckBox(“Show Help”, true);
JRadioButton


<생성자의 인자>
- 옆에 붙는 라벨 문자열
- default체크값(on= true)
*ButtonGroup으로 집합가능
ButtonGroup radioGroup = new ButtonGroup();
JRadioButton rb1 = new JRadioButton(“쉬움”, true);
JRadioButton rb2 = new JRadioButton(“중간”);
JRadioButton rb3 = new JRadioButton(“어려움”);
radioGroup.add(rb1);
radioGroup.add(rb2);
radioGroup.add(rb3);
JTextField

<생성자의 인자>
- 컴포넌트 설명하는 문자열
- 너비(=열의 갯수)
*글자수 제한 없음
JTextField txtBox = new JTextField(20);
JTextArea

<생성자의 인자>
- 컴포넌트 설명하는 문자열
- 높이(행 갯수), 너비(열 갯수)
JTextArea txtArea = new JTextArea(“This text is default text for text area.”, 5, 20);
JPasswordField
(extends JTextField)
JPasswordField pwdField = new JPasswordField(15);
var pwdValue = pwdField.getPassword();
JList
DefaultListItem cityList = new DefaultListItem();
cityList.addElement(“Mumbai”):
cityList.addElement(“London”):
cityList.addElement(“New York”):
cityList.addElement(“Sydney”):
cityList.addElement(“Tokyo”):
JList cities = new JList(cityList);
cities.setSelectionModel(ListSelectionModel.SINGLE_SELECTION);
JFileChooser
JFileChooser fileChooser = new JFileChooser();
JButton fileDialogBtn = new JButton(“Select File”);
fileDialogBtn.AddEventListner(new ActionListner(){
fileChooser.showOpenDialog();
})
var selectedFile = fileChooser.getSelectedFile();
JTabbedPane
JTabbedPane tabbedPane = new JTabbedPane();
tabbedPane.addTab(“Tab 1”, new JPanel());
tabbedPane.addTab(“Tab 2”, new JPanel());
JSlider
JSlider volumeSlider = new JSlider(0, 100, 50);
var volumeLevel = volumeSlider.getValue();

 

3-3) 그외

이름 그림
JProgressBar
JToolTip
JMenu

 




[참고]
- awt와 swing의 차이 - https://diaryofgreen.tistory.com/140
- 컴포넌트란? - https://mommoo.tistory.com/55
- 명우니닷컴 https://myeonguni.tistory.com/1006
- 가장 많이 사용하는 13가지 컴포넌트 https://www.educba.com/swing-components-in-java/
- JComboBox 콤보박스 - https://movefast.tistory.com/63
- JList https://lunaticlobelia.tistory.com/118
- JProgrssBar https://www.javatpoint.com/java-jprogressbar
- JToolTip https://log.hanjava.net/post/2466129264/jtooltip-%EC%9D%B4%EC%95%BC%EA%B8%B0-i
- JMenu https://www.javatpoint.com/java-jmenuitem-and-jmenu
- JDiaglog in java https://www.educba.com/jdialog-in-java/
- JFileChooser https://creatordev.tistory.com/51
- GUI개요 https://m.blog.naver.com/PostView.naver?isHttpsRedirect=true&blogId=sks6624&logNo=150164573882
- 알통몬의 인생 https://m.blog.naver.com/rain483/220735906752

[이클립스에서 템플릿 만들기]

[0] 저장할 소스를 긁어서 Ctrl+c로 복사합니다.

[1][2] [window] > [Preferences] 로 들어갑니다.

[3] 검색창에 "temp"를 쓰고,  [Java] > [Editor] > [Templates]로 이동합니다.

[4] [New]를 눌러 새 템플렛 만드는 창을 엽니다.

[5] 제목을 적어줍시다.

[6] 긁어온 코드를 Ctrl+v로 붙여줍니다.

[7] 클래스명을 드래그한 뒤 [Insert Variable]의 [Primary_type_name](환경변수)로 바꿔줍니다.

    *객체명의 경우 [Primary_type_name]

    *인자로 설정할 경우 [args]

[8] [Ok]를 눌러 완료한 뒤, [Apply]후 창을 빠져나옵니다.

 

[새로운 워크스페이스에 기존 템플릿을 넣기]

- Copy Settings에서 Preferences를 체크

Wrapper클래스

   Wrapper : Boolean, Byte, Integer, Long, Float, Double

 

Wrapper클래스의 오토-언박싱과 오토-박싱

   - Auto-Boxing : 

 

[Auto-Boxing 예제_Object객체배열 안에 다양한 타입의 기본형 리터럴 입력]

package mymain;

public class WrapperTest {

	public static void main(String[] args) {
		Object[] arr = {10, "String", 12.5, 'c'};
		//Object객체타입에 대입하면서, 각가의 리터럴이 실제로는 아래와 같이 오토박싱
		//arr[0] = new Integer(10);
		System.out.println(arr[0]);
		System.out.println(arr[1]);
		System.out.println(arr[2]);
		System.out.println(arr[3]);
	}

}

>> 실행결과

10
String
12.5
c

 

[Auto-UnBoxing 예제_Object객체배열 안에 다양한 타입의 기본형 리터럴 입력]

package mymain;

public class WrapperTest {

	public static void main(String[] args) {
		Object[] arr = {10, "String", 12.5, 'c'};
		int n = (Integer)arr[0];
		//1) Auto-Boxing : arr[0] = new Integer(10);
		//2) 참조타입 변경 : Object -> Integer (Down-Casting)
		//3) Auto-unboxing : int n = <<대입되면서 기본형으로 변경
		String s = (String)arr[1];
		double d = (double)arr[2];
		//(double)arr[2] ::형변환을 하면서 기본형으로 변경
		char c = (char)arr[3];
		System.out.println(n);
		System.out.println(s);
		System.out.println(d);
		System.out.println(c);
	}

}

>> 결과

10
String
12.5
c

[2차원 배열 예제_ 여러 방향으로 뒤집기]

 

1. 90도 회전하기

  [원리] *표시한 노란색 기준
  - 왼쪽의 열이 오른쪽 행로 바뀌었다. (반대로는, 오른쪽 행은 왼쪽의 열이다)
  - 왼쪽의 열은 0~4순번이며, 오른쪽 행도 0~4순번이다. (반대로도 동일)
  - 왼쪽의 행은 0으로 고정되었고, 오른쪽 열은 4로 고정되어 있다. 

[90도 회전 코드]

package myutil;

public class MultiArray {
	public static int[][] rotate90(int[][] arr){
		int row = arr.length, col = arr[0].length;		
		int[][] rotatedArr = new int[row][col];
		
		for(int i = 0; i < row; i++) {
			for(int j = 0; j < col; j++) {
				rotatedArr[i][j] = arr[(row-1)-j][i];
			}
		}
		return rotatedArr;
	}
}

[출력 코드]

package mymain;

import myutil.MultiArray;

public class MultiArrayTest {

	public static void main(String[] args) {
		int[][] arr = new int[5][5];
		int n = 1;
		for(int i = 0; i < arr.length; i++) {
			for(int j = 0; j < arr[0].length; j++) {
				arr[i][j] = n++;
			}
		}
		
		int[][] rotatedArr = MultiArray.rotate90(arr);
		
		n = 1;
		for(int i = 0; i < rotatedArr.length; i++) {
			for(int j = 0; j < rotatedArr[0].length; j++) {
				System.out.printf("%4d",rotatedArr[i][j]);
			}
			System.out.println();
		}
	}

}

>> 결과

  21  16  11   6   1
  22  17  12   7   2
  23  18  13   8   3
  24  19  14   9   4
  25  20  15  10   5

 

 

2. 좌우 바꾸기

  [원리] *표시한 색 기준
  - 왼쪽의 열의 0번째가 오른쪽 열의 4번째가 되었다.
  - 왼쪽의 열의 4번째가 오른쪽 열의 0번째가 되었다.  

[좌우 바꾸기 코드]

package myutil;

public class MultiArray {
	public static int[][] flip_leftRight(int[][] arr){
		int row = arr.length, col = arr[0].length;
		int[][] flipedArr = new int[row][col];
		
		for(int i = 0; i < row; i++) {
			for(int j = 0; j < col; j++) {
				flipedArr[i][j] = arr[i][(col-1)-j];
			}
		}
		return flipedArr;
	}
}

[출력 코드]

package mymain;

import myutil.MultiArray;

public class MultiArrayTest {

	public static void main(String[] args) {
		int[][] arr = new int[5][5];
		int n = 1;
		for(int i = 0; i < arr.length; i++) {
			for(int j = 0; j < arr[0].length; j++) {
				arr[i][j] = n++;
			}
		}
		
		int[][] rotatedArr = MultiArray.flip_leftRight(arr);
		
		n = 1;
		for(int i = 0; i < rotatedArr.length; i++) {
			for(int j = 0; j < rotatedArr[0].length; j++) {
				System.out.printf("%4d",rotatedArr[i][j]);
			}
			System.out.println();
		}
	}

}

>> 결과

   5   4   3   2   1
  10   9   8   7   6
  15  14  13  12  11
  20  19  18  17  16
  25  24  23  22  21

 

3. 위아래 바꾸기

  [원리] *표시한 노란색 기준
  - 왼쪽 행의 0번째가 오른쪽 행의 4번째
  - 왼쪽 행의 4번째가 오른쪽 행의 0번째

[위아래 바꾸기 코드]

package myutil;

public class MultiArray {
	public static int[][] flip_upDown(int[][] arr){
		int row = arr.length, col = arr[0].length;
		int[][] flipedArr = new int[row][col];
		
		for(int i = 0; i < row; i++) {
			for(int j = 0; j < col; j++) {
				flipedArr[i][j] = arr[(row-1)-i][j];
			}
		}
		return flipedArr;
	}
}

[출력 코드]

package mymain;

import myutil.MultiArray;

public class MultiArrayTest {

	public static void main(String[] args) {
		int[][] arr = new int[5][5];
		int n = 1;
		for(int i = 0; i < arr.length; i++) {
			for(int j = 0; j < arr[0].length; j++) {
				arr[i][j] = n++;
			}
		}
		
		int[][] rotatedArr = MultiArray.flip_upDown(arr);
		
		n = 1;
		for(int i = 0; i < rotatedArr.length; i++) {
			for(int j = 0; j < rotatedArr[0].length; j++) {
				System.out.printf("%4d",rotatedArr[i][j]);
			}
			System.out.println();
		}
	}

}

>> 결과

  21  22  23  24  25
  16  17  18  19  20
  11  12  13  14  15
   6   7   8   9  10
   1   2   3   4   5

 

4. 대각선(좌->우) 접기

  [원리] *표시한 노란색 기준
  - 왼쪽의 행이 오른쪽 열로 바뀌었다. 
  - 왼쪽의 행은 0~4순번이며, 오른쪽 열도 0~4순번이다.

[대각선(좌->우) 코드]

package myutil;

public class MultiArray {
	public static int[][] diagonal1(int[][] arr){
		int row = arr.length, col = arr[0].length;
		int[][] diagonalArr = new int[row][col];
		
		for(int i = 0; i < row; i++) {
			for(int j = 0; j < col; j++) {
				diagonalArr[i][j] = arr[j][i];
			}
		}
		return diagonalArr;
	}
}

[출력 코드]

package mymain;

import myutil.MultiArray;

public class MultiArrayTest {

	public static void main(String[] args) {
		int[][] arr = new int[5][5];
		int n = 1;
		for(int i = 0; i < arr.length; i++) {
			for(int j = 0; j < arr[0].length; j++) {
				arr[i][j] = n++;
			}
		}
		
		int[][] rotatedArr = MultiArray.diagonal1(arr);
		
		n = 1;
		for(int i = 0; i < rotatedArr.length; i++) {
			for(int j = 0; j < rotatedArr[0].length; j++) {
				System.out.printf("%4d",rotatedArr[i][j]);
			}
			System.out.println();
		}
	}

}

>> 결과

   1   6  11  16  21
   2   7  12  17  22
   3   8  13  18  23
   4   9  14  19  24
   5  10  15  20  25

 

5. 대각선(우->좌) 접기

  [원리] *표시한 노란색 기준
  - 왼쪽의 행이 오른쪽 열로 바뀌었다. 
  - 왼쪽 행의 0번째가 오른쪽 열의 4번째가 되었다.
  - 왼쪽 열은 0~4순번으로 간다. 오른쪽 행은 4~0순번이다.  

[대각선(우->좌) 코드]

package myutil;

public class MultiArray {
	public static int[][] diagonal2(int[][] arr){
		int row = arr.length, col = arr[0].length;
		int[][] diagonalArr = new int[row][col];
		
		for(int i = 0; i < row; i++) {
			for(int j = 0; j < col; j++) {
				diagonalArr[i][j] = arr[(row-1)-j][(col-1)-i];
			}
		}
		return diagonalArr;
	}
}

[출력 코드]

package mymain;

import myutil.MultiArray;

public class MultiArrayTest {

	public static void main(String[] args) {
		int[][] arr = new int[5][5];
		int n = 1;
		for(int i = 0; i < arr.length; i++) {
			for(int j = 0; j < arr[0].length; j++) {
				arr[i][j] = n++;
			}
		}
		
		int[][] rotatedArr = MultiArray.diagonal2(arr);
		
		n = 1;
		for(int i = 0; i < rotatedArr.length; i++) {
			for(int j = 0; j < rotatedArr[0].length; j++) {
				System.out.printf("%4d",rotatedArr[i][j]);
			}
			System.out.println();
		}
	}

}

>> 결과

  25  20  15  10   5
  24  19  14   9   4
  23  18  13   8   3
  22  17  12   7   2
  21  16  11   6   1

 

6. 더블 크로스

  [원리] *표시한 색 기준
  - 왼쪽의 0행은 오른쪽에서 4행
  - 왼쪽의 0열은 오른쪽에서 4열

[더블 크로스 코드]

package myutil;

public class MultiArray {
	public static int[][] doubleCross(int[][] arr){
		int row = arr.length, col = arr[0].length;
		int[][] xArr = new int[row][col];
		
		for(int i = 0; i < row; i++) {
			for(int j = 0; j < col; j++) {
				xArr[i][j] = arr[(row-1)-i][(col-1)-j];
			}
		}
		return xArr;
	}
}

[출력 코드]

package mymain;

import myutil.MultiArray;

public class MultiArrayTest {

	public static void main(String[] args) {
		int[][] arr = new int[5][5];
		int n = 1;
		for(int i = 0; i < arr.length; i++) {
			for(int j = 0; j < arr[0].length; j++) {
				arr[i][j] = n++;
			}
		}
		
		int[][] rotatedArr = MultiArray.doubleCross(arr);
		
		n = 1;
		for(int i = 0; i < rotatedArr.length; i++) {
			for(int j = 0; j < rotatedArr[0].length; j++) {
				System.out.printf("%4d",rotatedArr[i][j]);
			}
			System.out.println();
		}
	}

}

>> 결과

  25  24  23  22  21
  20  19  18  17  16
  15  14  13  12  11
  10   9   8   7   6
   5   4   3   2   1

class Exercise3_1 { 
	public static void main(String[] args) { 
		int x = 2; 
		int y = 5; 
		char c = 'A'; // 'A'의 문자코드는 65 
		System.out.println(1 + x << 33); 
		System.out.println(y >= 5 || x < 0 && x > 2); 
		System.out.println(y += 10 - x++); 
		System.out.println(x+=2); 
		System.out.println( !('A' <= c && c <='Z') ); 
		System.out.println('C'-c); 
		System.out.println('5'-'0'); 
		System.out.println(c+1); 
		System.out.println(++c); 
		System.out.println(c++); 
		System.out.println(c); 
	} 
}

 

더보기

6

true

13

5

false

2

5

66

B

B

C

 

class Exercise3_2 { 
	public static void main(String[] args) { 
		int numOfApples = 123; // 사과의 개수 
		int sizeOfBucket = 10; // 바구니의 크기 (바구니에 담을 수 있는 사과의 개수)
		int numOfBucket = ( /* (1) */ ) ;

		System.out.println("필요한 바구니의 수 :"+numOfBucket);
	}
}

>> 실행결과

13
더보기

[3-2] X
//나 : numOfApples/sizeOfBucket+(numOfApples%sizeOfBucket==0? 0 : 1)
답 : numOfApples/sizeOfBucket+(numOfApples%sizeOfBucket>0? 1 : 0)

 

class Exercise3_3 { 
	public static void main(String[] args) { 
		int num = 10; 
		System.out.println( /* (1) */ ); 
	} 
}

>> 실행결과

양수
더보기

[3-3]
num < 0? "음수" : "양수";

 

class Exercise3_4 { 
	public static void main(String[] args) { 
		int num = 456; 
		System.out.println( /* (1) */ ); 
	} 
}

>> 실행결과

400
더보기

[3-4]
num/100*100

 

class Exercise3_5 {
	public static void main(String[] args) {
		int num = 333;
		System.out.println( /* (1) */);
	}
}

>> 실행결과

331
더보기

[3-5]
num/10*10+1

 

class Exercise3_6 {
	public static void main(String[] args) {
		int num = 24;
		System.out.println( /* (1) */);
	}
}

>> 실행결과

6
더보기

[3-6] X
//나 : (num/10+1)*10-num
답 : 10 - num%10

 

class Exercise3_7 {
	public static void main(String[] args) { 
		int fahrenheit = 100; 
		float celcius = ( /* (1) */ );
		
		System.out.println("Fahrenheit:"+fahrenheit); 
		System.out.println("Celcius:"+celcius); 
	}
}

>> 실행결과

Fahrenheit:100
Celcius:37.78
더보기

[3-7] X
//나 : ((int)(5f/9*(fahrenheit-32)*100+0.5f))/100f
답 : (int)(5f/9*(fahrenheit-32)*100+0.5)/100f

 

class Exercise3_8 {
	public static void main(String[] args) {
		byte a = 10;
		byte b = 20;
		byte c = a + b;
		char ch = 'A';
		ch = ch + 2;
		float f = 3 / 2;
		long l = 3000 * 3000 * 3000;
		float f2 = 0.1f;
		double d = 0.1;
		boolean result = d == f2;
		System.out.println("c=" + c);
		System.out.println("ch=" + ch);
		System.out.println("f=" + f);
		System.out.println("l=" + l);
		System.out.println("result=" + result);
	}
}

>> 결과

c=30
ch=C
f=1.5
l=27000000000
result=true
더보기

[3-8]
byte c = (byte)(a + b);
ch = (char)(ch + 2);
// 나 : float f = 3f/2;

float f = 3/2f
// 나 : long l = 3000L*3000*3000;

long l = 3000*3000*3000L
boolean result = (float)d == f2;

 

class Exercise3_9 {
	public static void main(String[] args) { 
		char ch = 'z'; 
		boolean b = ( /* (1) */ ); 
		System.out.println(b); 
	}
}

>> 결과

true
더보기

[3-9] X
//나 : (ch >= 'A' && ch <= 'Z') || (ch >= 'a' && ch <= 'z') || (ch >= '0' && ch <= '9')? true : false;
답 : (ch >= 'A' && ch <= 'Z') || (ch >= 'a' && ch <= 'z') || (ch >= '0' && ch <= '9')

 

class Exercise3_10 {
	public static void main(String[] args) { 
		char ch = 'A'; 
		char lowerCase = ( /* (1) */ ) ? ( /* (2) */ ) : ch; 
		System.out.println("ch:"+ch); 
		System.out.println("ch to lowerCase:"+lowerCase); 
	} 
}

>> 결과

ch:A
ch to lowerCase:a
더보기

[3-10] X
(1) (ch >= 'A' && ch<='Z')
//나 : (2) ch-32
답 : (2) (char)ch-32

더보기
  1byte 2byte 4byte 8byte
논리형 boolean      
문자형   char    
정수형 byte short int long
실수형     float double

 

더보기
long regNo = 6011221324355L;

[ 해설]  정수형 타입으로는 보통  int형을 사용하지만 주민등록번호는 13자리의 정수이기 때문에 int형의 범위를 넘어서는 값이다 그래서 형을 사용해야한다 그리고 리터럴  'L' 의 접미사 을 잊어서는 안된다.

* int형은 -20억 ~ 20억까지 가능 (-10자리~10자리)'

*long형은 -19자리 ~ 19자리

 

더보기

- 리터럴 : 100, 100L, 3.14f

- 변수 : i, l

- 키워드 : int, long, final, float

- 상수 : PI

더보기

b. Byte (Byte클래스이다.)

 

더보기

12

true

131

51

99

Java

오류

 

더보기

b, c, d, e

 

더보기

a, d, e, g

 

더보기

a, d

 

 

더보기

d, e

*byte의 범위 : -128~127, short의 범위 : -3만~3만, int의 범위 : -20억 ~ 20억(-10자리~10자리), long의 범위 : 20자리

*char의 범위 : 0~66535 (5자리)

*실수형 <- 정수형 : 실수형의 저장범위가 정수형 보다 커서 자동형변환 가능 (그러나 정밀도가 다르므로 유의)

 

더보기

0~66535

 

더보기

a, b, c, d

 

더보기

a, b, c, e

 

더보기

c, e, f

[5-1] 다음은 배열을 선언하거나 초기화한 것이다 잘못된 것을 고르고 그 이유를 설명하시오. 

a. int[] arr[];
b. int[] arr = {1,2,3,};
c. int[] arr = new int[5];
d. int[] arr = new int[5]{1,2,3,4,5};
e. int arr[5];
f. int[] arr[] = new int[3][];  
더보기
답) d,e

이유)

d : new int[ ]의 [ ] 안에 배열의 갯수를 지정할 수 없다.

e : [ ]안에 갯수를 넣을 수 없다.



*f. int[] arr[] = new int[3][];  //이건 가능한데, int[] arr[] = new int[][3]; 는 불가능

 

[5-2] 다음과 같은 배열이 있을 때 arr[3].length의 값은 얼마인가 , 

int[][] arr = {
    { 5, 5, 5, 5, 5},
    { 10, 10, 10},
    { 20, 20, 20, 20},
    { 30, 30}
}
더보기

답)

2

 

[5-3] 배열에 담긴 모든 값을 더하는 프로그램을 완성하시오. (실행결과 : 150)

class Exercise5_3
{
    public static void main(String[] args)
    {
        int[] arr = {10, 20, 30, 40, 50};
        int sum = 0;
        /*
            (1) . 알맞은 코드를 넣어 완성하시오
        */
        System.out.println("sum="+sum);
    }
}

 

더보기

답)

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

 

 

[5-4] 2차원 배열에 담긴 모든 값의 총합과 평균을 구하는 프로그램을 완성하시오

(실행 결과 : 

total=325
average=16.25)

package arrayex;

class Exercise5_4
{
	public static void main(String[] args)
	{
		int[][] arr = {
			{ 5, 5, 5, 5, 5},
			{10,10,10,10,10},
			{20,20,20,20,20},
			{30,30,30,30,30}
		};
		int total = 0;
		float average = 0;
		/*
		(1) . 알맞은 코드를 넣어 완성하시오
		*/
		System.out.println("total="+total);
		System.out.println("average="+average);
	} // end of main
} // end of class

 

더보기

답)

int total_length = 0;
		
for(int i = 0; i < arr.length; i++) {
    for(int j = 0; j < arr[i].length; j++) {
        total += arr[i][j];
        total_length++;
    }
}

average = (float)(total/total_length);

 

 

 

[5-5] 다음은 과 사이의 중복되지 않은 숫자로 이루어진 자리 숫자를 만들어내는 프로그램이다 (1)~(2) 에 알맞은 코드를 넣어서 프로그램을 완성하시오 . 

package arrayex;

class Exercise5_4 {
public static void main(String[] args) {
		int[] ballArr = {1,2,3,4,5,6,7,8,9};
		int[] ball3 = new int[3];
		
		// ballArr . 배열 의 임의의 요소를 골라서 위치를 바꾼다
		for(int i=0; i< ballArr.length;i++) {
			int j = (int)(Math.random() * ballArr.length);
			int tmp = 0;
			/*
			(1) . 알맞은 코드를 넣어 완성하시오
			*/
		}
		// ballArr 3 ball3 . 배열 의 앞에서 개의 수를 배열 로 복사한다
		/* (2) */
		for(int i=0;i<ball3.length;i++) {
			System.out.print(ball3[i]);
		}
	} // end of main
} // end of class
더보기

답)

package arrayex;

class Exercise5_4 {
public static void main(String[] args) {
		int[] ballArr = {1,2,3,4,5,6,7,8,9};
		int[] ball3 = new int[3];
		
		// 배열 ballArr의 임의의 요소를 골라서 위치를 바꾼다
		for(int i=0; i< ballArr.length;i++) {
			int j = (int)(Math.random() * ballArr.length);
			int tmp = 0;
			tmp = ballArr[i];
			ballArr[i] = ballArr[j];
			ballArr[j] = tmp;
		}
		//  배열 ballArr 의 앞에서 3 개의 수를 배열 ball3로 복사한다
		System.arraycopy(ballArr, 0, ball3, 0, 3);
		
		for(int i=0;i<ball3.length;i++) {
			System.out.print(ball3[i]);
		}
	} // end of main
} // end of class

 

[5-6] 다음은 거스름돈을 몇 개의 동전으로 지불할 수 있는지를 계산하는 문제이다. 변수 money의 금액을 동전으로 바꾸었을 때 각각 몇 개의 동전이 필요한지 계산해서 출력하라 (단, 가능한 한 적은 수의 동전으로 거슬러 주어야한다.)

(1)에 알맞은 코드를 넣어서 프로그램을 완성하시오.

package arrayex;

class Exercise5_6 {
public static void main(String args[]) {
		// . 큰 금액의 동전을 우선적으로 거슬러 줘야한다
		int[] coinUnit = {500, 100, 50, 10};
		
		int money = 2680;
		System.out.println("money="+money);
		
		for(int i=0;i<coinUnit.length;i++) {
		/*
		(1) . 알맞은 코드를 넣어 완성하시오
		*/
		}
	} // main
}

>> 실행결과

money=2680
500 : 5 원
100 : 1 원
50 : 1 원
10 : 3
더보기

답)

for(int i=0;i<coinUnit.length;i++) {
    if(money >= coinUnit[i]) {
        System.out.printf("%d원:%d%n",coinUnit[i],money/coinUnit[i]);
        money = money%coinUnit[i];
    }
}

 

[5-7] 문제 5-6에 동전의 개수를 추가한 프로그램이다. 커맨드라인으로부터 거슬러 줄 금액을 입력받아 계산한다. 보유한 동전의 개수로 거스름돈을 지불할 수 없으면, '거스름돈이 부족합니다.'라고 출력하고 종료한다. 지불할 돈이 충분히 있으면, 거스름돈을 지불한 만큼 가진 돈에서 빼고 남은 동전의 개수를 화면에 출력한다. (1)에 알맞은 코드를 넣어서 프로그램을 완성하시오.

class Exercise5_7 {
	public static void main(String args[]) {
		if (args.length != 1) {
			System.out.println("USAGE: java Exercise5_7 3120");
			System.exit(0);
		}

		// 문자열을 숫자로 변환한다. 입력한 값이 숫자가 아닐 경우 예외가 발생한다.
		int money = Integer.parseInt(args[0]);

		System.out.println("money=" + money);

		int[] coinUnit = { 500, 100, 50, 10 }; // 동전의 단위
		int[] coin = { 5, 5, 5, 5 }; // 단위별 동전의 개수

		for (int i = 0; i < coinUnit.length; i++) {
			int coinNum = 0;
			/*
			 * (1)아래의 로직에 맞게 코드를 작성하시오. 
			 * 1. 금액(money)을 동전단위로 나눠서 필요한 동전의 개수(coinNum)를 구한다. 
			 * 2. 배열 coin에서 coinNum만큼의 동전을 뺀다. (만일 충분한 동전이 없다면 배열 coin에 있는 만큼만 뺀다.) 
			 * 3. 금액에서 동전의 개수(coinNum)와 동전단위를 곱한 값을 뺀다.
			 */

			System.out.println(coinUnit[i] + "원: " + coinNum);
		}

		if (money > 0) {
			System.out.println("거스름돈이 부족합니다 ");
			System.exit(0); // 프로그램을 종료한다.
		}
		System.out.println("= 남은 동전의 개수 =");

		for (int i = 0; i < coinUnit.length; i++) {
			System.out.println(coinUnit[i] + "원:" + coin[i]);
		}
	} // main
}

>> 실행결과

C:\jdk1.8\work\ch5>java Exercise5_7
USAGE: java Exercise5_7 3120
C:\jdk1.8\work\ch5>java Exercise5_7 3170
money=3170
500 : 5 원
100 : 5 원
50 : 3 원
10 : 2 원
= = 남은 동전의 개수
500 :0 원
100 :0 원
50 :2 원
10 :3 원
C:\jdk1.8\work\ch5>java Exercise5_7 3510
money=3510
500 : 5 원
100 : 5 원
50 : 5 원
10 : 5 원
거스름돈이 부족합니다.
더보기
class Exercise5_7 {
	public static void main(String args[]) {
		if (args.length != 1) {
			System.out.println("USAGE: java Exercise5_7 3120");
			System.exit(0);
		}

		// 문자열을 숫자로 변환한다. 입력한 값이 숫자가 아닐 경우 예외가 발생한다.
		int money = Integer.parseInt(args[0]);

		System.out.println("money=" + money);

		int[] coinUnit = { 500, 100, 50, 10 }; // 동전의 단위
		int[] coin = { 5, 5, 5, 5 }; // 단위별 동전의 개수

		for (int i = 0; i < coinUnit.length; i++) {
			int coinNum = 0;

			coinNum = money % coinUnit[i];
			coin[i] -= coinNum;
			money -= coinUnit[i]*coinNum;

			System.out.println(coinUnit[i] + "원: " + coinNum);
		}

		if (money > 0) {
			System.out.println("거스름돈이 부족합니다 ");
			System.exit(0); // 프로그램을 종료한다.
		}
		System.out.println("= 남은 동전의 개수 =");

		for (int i = 0; i < coinUnit.length; i++) {
			System.out.println(coinUnit[i] + "원:" + coin[i]);
		}
	} // main
}

 

[5-8] 다음은 배열 answer에 담긴 데이터를 읽고 각 숫자의 개수를 세어서 개수만큼 '*'을 찍어서 그래프를 그리는 프로그램이다. (1)~(2)에 알맞은 코드를 넣어서 완성하시오.

class Exercise5_8 {
	public static void main(String[] args) {
		int[] answer = { 1, 4, 4, 3, 1, 4, 4, 2, 1, 3, 2 };
		int[] counter = new int[4];
		for (int i = 0; i < answer.length; i++) {
			/* (1) 알맞은 코드를 넣어 완성하시오. */
		}
		for (int i = 0; i < counter.length; i++) {
			/* 알맞은 코드를 넣어 완성하시오 (2) . */
			System.out.println();
		}
	}
}

>> 실행결과

3***
2**
2**
4****
더보기
class Exercise5_8 {
	public static void main(String[] args) {
		int[] answer = { 1, 4, 4, 3, 1, 4, 4, 2, 1, 3, 2 };
		int[] counter = new int[4];
		
		for (int i = 0; i < answer.length; i++) {
			counter[answer[i]-1]++;
		}
		for (int i = 0; i < counter.length; i++) {
			System.out.print(counter[i]+":");
			for(int j = 0; j < counter[i]; j++){
				System.out.print("*");
			}
			System.out.println();
		}
	}
}

 

[5-9] 주어진 배열을 시계방향으로 90도 회전시켜서 출력하는 프로그램을 완성하시오.

class Exercise5_9 {
	public static void main(String[] args) {
		char[][] star = { 
				{ '*', '*', ' ', ' ', ' ' },
				{ '*', '*', ' ', ' ', ' ' }, 
				{ '*', '*', '*', '*', '*' },
				{ '*', '*', '*', '*', '*' } 
		};
		char[][] result = new char[star[0].length][star.length];
		for (int i = 0; i < star.length; i++) {
			for (int j = 0; j < star[i].length; j++) {
				System.out.print(star[i][j]);
			}
			System.out.println();
		}
		System.out.println();
		for (int i = 0; i < star.length; i++) {
			for (int j = 0; j < star[i].length; j++) {
				/* 알맞은 코드를 넣어 완성하시오 (1) . */
			}
		}
		for (int i = 0; i < result.length; i++) {
			for (int j = 0; j < result[i].length; j++) {
				System.out.print(result[i][j]);
			}
			System.out.println();
		}
	}
}

>> 실행결과

** 
**
***** 
*****

**** 
**** 
** 
** 
**
더보기
package arrayex;

public class Exercise5_9 {

public static void main(String[] args) {
		char[][] star = { 
				{ '*', '*', ' ', ' ', ' ' },
				{ '*', '*', ' ', ' ', ' ' }, 
				{ '*', '*', '*', '*', '*' },
				{ '*', '*', '*', '*', '*' } 
		};
		char[][] result = new char[star[0].length][star.length];
		for (int i = 0; i < star.length; i++) {
			for (int j = 0; j < star[i].length; j++) {
				System.out.print(star[i][j]);
			}
			System.out.println();
		}
		System.out.println();
		for (int i = 0; i < star.length; i++) {
			for (int j = 0; j < star[i].length; j++) {
				result[j][star.length-1-i]=star[i][j];
			}
		}
		for (int i = 0; i < result.length; i++) {
			for (int j = 0; j < result[i].length; j++) {
				System.out.print(result[i][j]);
			}
			System.out.println();
		}
	}

}

 

[5-10] 다음은 알파벳과 숫자를 아래에 주어진 암호표로 암호화하는 프로그램이다. (1)에 알맞은 코드를 넣어서 완성하시오.

class Exercise5_10 {
	public static void main(String[] args) {
		char[] abcCode = { '`', '~', '!', '@', '#', '$', '%', '^', '&', '*',
				'(', ')', '-', '_', '+', '=', '|', '[', ']', '{', '}', ';',
				':', ',', '.', '/' };
						 // 0	 1	  2	   3    4    5    6    7    8    9 
		char[] numCode = { 'q', 'w', 'e', 'r', 't', 'y', 'u', 'i', 'o', 'p' };

		String src = "abc123";
		String result = "";

		// 문자열 src의 문자를 charAt()으로 하나씩 읽어서 변환 후 result에 저장
		for (int i = 0; i < src.length(); i++) {
			char ch = src.charAt(i);
			/* (1) 알맞은 코드를 넣어 완성하시오 . */
		}

		System.out.println("src:" + src);
		System.out.println("result:" + result);
	} // end of main
} // end of class

>> 실행결과

src:abc123 
result:`~!wer
더보기
package arrayex;

public class Exercise5_10 {

	public static void main(String[] args) {
		char[] abcCode = { '`', '~', '!', '@', '#', '$', '%', '^', '&', '*',
				'(', ')', '-', '_', '+', '=', '|', '[', ']', '{', '}', ';',
				':', ',', '.', '/' };
						 // 0	 1	  2	   3    4    5    6    7    8    9 
		char[] numCode = { 'q', 'w', 'e', 'r', 't', 'y', 'u', 'i', 'o', 'p' };

		String src = "abc123";
		String result = "";
		StringBuffer buffer = new StringBuffer(src.length());

		// 문자열 src의 문자를 charAt()으로 하나씩 읽어서 변환 후 result에 저장
		for (int i = 0; i < src.length(); i++) {
			char ch = src.charAt(i);
			if(ch >= '0' && ch <='9') {
				buffer.append(numCode[ch-'0']);
			}else {
				buffer.append(abcCode[ch-'a']);
			}
		}
		result = buffer.toString();

		System.out.println("src:" + src);
		System.out.println("result:" + result);
	}

}

 

[5-11] 주어진 2차원 배열의 데이터보다 가로와 세로로 1이 더 큰 배열을 생성해서 배열의 행과 열의 마지막 요소에 각 열과 행의 총합을 저장하고 출력하는 프로그램이다. (1)에 알맞은 코드를 넣어서 완성하시오.

class Exercise5_11 {
	public static void main(String[] args) {
		int[][] score = { 
				{ 100, 100, 100 }, 
				{ 20, 20, 20 }, 
				{ 30, 30, 30 },
				{ 40, 40, 40 }, 
				{ 50, 50, 50 } 
			};
		int[][] result = new int[score.length + 1][score[0].length + 1];
		
		for (int i = 0; i < score.length; i++) {
			for (int j = 0; j < score[i].length; j++) {
				
				/* 알맞은 코드를 넣어 완성하시오 (1) . */
				
			}
		}
		
		for (int i = 0; i < result.length; i++) {
			for (int j = 0; j < result[i].length; j++) {
				System.out.printf("%4d", result[i][j]);
			}
			System.out.println();
		}
	} // main }
}

>> 실행결과

100 100 100 300 
20 20 20 60 
30 30 30 90 
40 40 40 120 
50 50 50 150 
240 240 240 720
더보기
package arrayex;

public class Exercise5_11 {

	public static void main(String[] args) {
		int[][] score = { 
				{ 100, 100, 100 }, 
				{ 20, 20, 20 }, 
				{ 30, 30, 30 },
				{ 40, 40, 40 }, 
				{ 50, 50, 50 } 
			};
		int[][] result = new int[score.length + 1][score[0].length + 1];
		
		for (int i = 0; i < score.length; i++) {
			for (int j = 0; j < score[i].length; j++) {
					result[i][j] = score[i][j];
					result[i][score[i].length]+=result[i][j];
					result[score.length][j] += result[i][j];
					result[score.length][result[0].length-1] += result[i][j];
			}
		}
		
		for (int i = 0; i < result.length; i++) {
			for (int j = 0; j < result[i].length; j++) {
				System.out.printf("%4d", result[i][j]);
			}
			System.out.println();
		}
	}

}

 

[5-13] 단어의 글자위치를 섞어서 보여주고 원래의 단어를 맞추는 예제이다. 실행결과와 같이 동작하도록 예제의 빈 곳을 채우시오.

import java.util.Scanner;

class Exercise5_13 {
	public static void main(String args[]) {
		String[] words = { "television", "computer", "mouse", "phone" };

		Scanner scanner = new Scanner(System.in);

		for (int i = 0; i < words.length; i++) {
			char[] question = words[i].toCharArray(); // String을 char[]로 변환

			/*
			 * (1) 알맞은 코드를 넣어 완성하시오 . char배열 question에 담긴 문자의 위치를 임의로 바꾼다.
			 */

			System.out.printf("Q%d. %s의 정답을 입력하세요 .>", i + 1, new String(
					question));
			String answer = scanner.nextLine();

			// trim()으로 answer의 좌우 공백을 제거한 후 , equals로 word[i]와 비교
			if (words[i].equals(answer.trim()))
				System.out.printf("맞았습니다.%n%n");
			else
				System.out.printf("틀렸습니다.%n%n");
		}
	} // main의 끝
}

>> 실행결과

Q1. lvtsieeoin의 정답을 입력하세요.>television 
맞았습니다.

Q2. otepcumr의 정답을 입력하세요.>computer 
맞았습니다.

Q3. usemo 의 정답을 입력하세요.>asdf 
틀렸습니다.
Q4. ohpne 의 정답을 입력하세요.>phone 
맞았습니다.
더보기
package arrayex;

import java.util.Scanner;

class Exercise5_13 {
	public static void main(String args[]) {
		String[] words = { "television", "computer", "mouse", "phone" };

		Scanner scanner = new Scanner(System.in);

		for (int i = 0; i < words.length; i++) {
			char[] question = words[i].toCharArray(); // String을 char[]로 변환

			for(int j = 0; j < question.length; j++) {
				char tmp = ' ';
				int ran = (int)(Math.random()*question.length);
				tmp = question[j];
				question[j] = question[ran];
				question[ran] = tmp;
			}

			System.out.printf("Q%d. %s의 정답을 입력하세요 .>", i + 1, new String(
					question));
			String answer = scanner.nextLine();

			// trim()으로 answer의 좌우 공백을 제거한 후 , equals로 word[i]와 비교
			if (words[i].equals(answer.trim()))
				System.out.printf("맞았습니다.%n%n");
			else
				System.out.printf("틀렸습니다.%n%n");
		}
	} // main의 끝
}

 

 

[참조]

- [자바의 정석], 남궁석 지음

- 블로그 https://codechobo.tistory.com/1

 

+ Recent posts