용어정리
본문정리
반복문
for, while, do~while c언어랑 같다.
하지만 for(int i = 0; i < 10; i++, System.out.print(i))가 가능하다.
c = (char)(c+1)로 입력해야 디버깅이 된다.
continue문과 break문
특별한게 없어요.
배열
배열에 대한 레퍼런스 변수를 선언 한 후 배열을 생성(배열의 저장 공간 할당)한다.
레퍼런스는 배열 공간에 대한 주소 값을 가진다.(그 자체가 배열은 아니다.)
치환 시 배열을 복사되는 것이 아니라, 래퍼런스 즉 배열에 대한 주소만 복사한다.
자바는 배열을 객체로 다룬다.(무슨 의미인지 잘 모르겠다 c는 포인터인데 흠...)
for-each는 각 원소를 순차적으로 접근한다는 것이다.
for( 변수 : 배열레퍼런스){반복작업문}
다차원 배열
메소드에서 배열 리턴
메소드에서 배열을 리턴하는 경우 배열에 대한 레퍼런스만 리턴된다. 즉, 변수의 타입이 일치해야한다.
main() 메소드
public 속성은 메소드가 다른 클래스에서 호출 가능함을 나타낸다. 자바 응용 프로그램이 실행을 시작할 때 자바 가상 기계에 의해 호출되어야 하므로 public으로 선언되어야 한다.
static 속성은 자신을 포함하는 클래스의 객체가 생성되기 전에 쓸 수 있다는 의미이다.
String[]은 자바는 명령행에 입력된 인자들을 문자열 배열로 만들어 main 메소드에 전달한다.
자바의 예외처리
try{ 예외가 발생할 가능성이 있는 실행문 }
catch(처리할 예외 타입 선언){ 예외 처리문 }
finally{ 예외 발생 여부와 상관없이 무조건 실행되는 문장 }
ArithmetricException : 정수를 0으로 나눌 때 발생
NullPointerException : null 레퍼런스를 참조할 때 발생
ArithmetricException e를 catch에 넣으면 객체 e에 예외 정보가 넘어온다.
연습문제
p.127 Q.1 2중 중첩을 사용하여 오른쪽과 같이 출력되도록 for, while, do~while 문으로 각각 프로그램을 작성하라.
***** \n****\n***\n**\n*
public class loop {
public static void main(String[] args) {
for(int i = 0; i<5; i++) {
for(int j = 0; j <5-i ; j++) {
System.out.print("*");
}
System.out.println();
}
}
}
public class loop {
public static void main(String[] args) {
int i = 0;
int j = 5;
while(i < 5) {
while(0 < j) {
System.out.print("*");
j--;
}
System.out.println();
i++;
j = 5 - i;
}
}
}
public class loop {
public static void main(String[] args) {
int i = 0;
int j = 5;
do {
do {
System.out.print("*");
j--;
}while(0 < j);
System.out.println();
i++;
j = 5 - i;
}while(i < 5);
}
}
Q2. for(;;);을 실행하면 어떻게 되는가?
무한 반복문이다.
Q3. 1부터 100까지 3의 배수의 합을 구하는 프로그램을 작성하라.
public class loop {
public static void main(String[] args) {
int sum = 0;
for(int i = 1; i <= 100; i++) {
if(i%3 == 0)
sum+=i;
}
System.out.print(sum);
}
}
p.137 Q1. 10개의 정수를 저장하는 배열 tenAarray을 선언하고 생성하는 코드를 작성하라.
int tenArray [] = new int[10];
Q2. 배열 tenArray의 크기를 어떻게 알아낼 수 있는가?
tenArray.length
Q3. 배열 tenAarray에 1~10까지 저장한 뒤, 모든 원소의 값을 더하여 출력하는 프로그램을 작성하라.
public class loop {
public static void main(String[] args) {
int tenArray [] = new int[10];
int sum = 0;
for(int i = 0; i < 10; i++) {
tenArray[i] = i + 1;
sum += tenArray[i];
}
System.out.print(sum);
}
}
p145. Q1. 다음 중 배열 선언과 생성이 옳은 것은?
int a[] = new int[5];
Q2. int 형 원소를 갖는 2 * 3 크기의 2차원 배열을 생성하라.
int a[][] = new int[2][3];
Q4. 다음 그림과 같은 구조와 값을 갖는 비정방형 배열을 생성하라
0 1 2 3
4
5
6 7 8 9
public class loop {
public static void main(String[] args) {
int a[][] = new int[4][];
a[0] = new int[4];
a[1] = new int[1];
a[2] = new int[1];
a[3] = new int[4];
a[0][0] = 0;
a[0][1] = 1;
a[0][2] = 2;
a[0][3] = 3;
a[1][0] = 4;
a[2][0] = 5;
a[3][0] = 6;
a[3][1] = 7;
a[3][2] = 8;
a[3][3] = 9;
}
}
p149. Q1. main() 메소드의 매개변수 타입은 무엇인가?
String
Q2. main() 메소드에서 사용자가 입력한 명령행 인자의 개수를 알아내는 방법은?
args.length
본문제
Q1. 1 3 5 7 9
Q3. continue
Q4. i == 51
Q7. 배열을 선언하고 생성하는 다음 물음에 답하라.
1) char c[] = new char[10];
2) int n[] = {0, 1, 2, 3, 4, 5}
3) char day[] = {'일', '월', '화', '수', '목', '금', '토'}
Q8. 배열을 선언하고 생성하는 다음 물음에 답하라.
1) boolean bool[] = {true, false, false, true}
2) double d[][] = new double[5][4]
3) int val[][] = { {1,2,3},{4,5,6}, {7,8,9}, {10,11,12} }
Q1.
int sum=0,i=0;
while(i<100){
sum += i; i+=2;}
System.out.println(sum);
해당 내용을 반복문을 통해 구현하라
public class WhileTest {
public static void main(String[] args) {
int sum = 0, i = 0;
while(i<100) {
sum += i;
i += 2;
}
System.out.println(sum);
}
}
public class WhileTest {
public static void main(String[] args) {
int sum = 0, i = 0;
for(i =0; i<100; i+= 2) {
sum += i;
}
System.out.println(sum);
}
}
public class WhileTest {
public static void main(String[] args) {
int sum = 0, i = 0;
do {
sum+=i;
i+=2;
}while(i<100);
System.out.println(sum);
}
}
Q2. 밑의 코드를 구현하라
1
1 2 3
1
1 2 3 4
1 2
public class WhileTest {
public static void main(String[] args) {
int n [][] = new int[5][];
n[0] = new int[1];
n[1] = new int[3];
n[2] = new int[1];
n[3] = new int[4];
n[4] = new int[2];
for(int i = 0; i < n.length; i++) {
int k = 0;
for(int j = 0; j < n[i].length; j++) {
n[i][j] = ++k;
System.out.print(n[i][j] + " ");
}
System.out.println("");
}
}
}
Q3. 밑의 코드를 구현하라
정수를 입력하시오>>4
****
***
**
*
import java.util.Scanner;
public class makestar {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("정수를 입력하시오>>");
int k = sc.nextInt();
for(int i = k; i > 0; i--) {
for(int j = 0; j < i; j++) {
System.out.print("*");
}
System.out.println("");
}
}
}
Q4. 밑의 코드를 구현하라
소문자 알파멧 하나를 입력하시오>>c
abc
ab
a
import java.util.Scanner;
public class makestar {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("소문자 알파벳 하나를 입력하시오>>");
String s = sc.next();
char c = s.charAt(0);
for(int i = 0; i <= c - 'a';i++) {
for(char j = 'a'; j <= (char)(c - i); j++) {
System.out.print(j);
}
System.out.println();
}
}
}
Q5. 양의 정수를 10개 입력받아 배열에 저장하고, 배열에 있는 정수 중에서 3의 배수만 출력하는 프로그램을 작성하라.
package loop;
import java.util.Scanner;
public class makestar {
public static void main(String[] args) {
int s[] = new int[10];
Scanner sc = new Scanner(System.in);
System.out.print("양의 정수 10개를 입력하시오>>");
for(int i =0; i < s.length; i++)
s[i] = sc.nextInt();
System.out.print("3의 배수는 ");
for(int i = 0; i < s.length; i++) {
if(s[i]%3 == 0)
System.out.print(s[i]+ " ");
}
}
}
Q6. 키보드에서 정수로 된 돈의 액수를 입력받아 오만원권, 만원권, 천원권, 500원, 100원, 50원, 10원, 1원짜리 동전이 각 몇개로 변환되는 지 출력하라.
import java.util.Scanner;
public class calc {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int unit[] = {50000, 10000, 1000, 500, 100, 50, 10, 1};
System.out.print("금액을 앱력하시오>>");
int won = sc.nextInt();
for(int i = 0; i < unit.length; i++) {
int k = won / unit[i];
if(k != 0) {
System.out.print(unit[i] + "원 짜리 : " + k + "개");
System.out.println();
}
won = won % unit[i];
}
}
}
Q7. 정수를 10개 저장하는 배열을 만들고 1에서 10까지 범위의 정수를 랜덤하게 생성하여 배열에 저장하라. 그리고 배열에 든 숫자들과 평균을 출력하라.
public class average {
public static void main(String[] args) {
double sum = 0;
System.out.print("랜덤한 정수들 : ");
for(int i = 0; i < 10; i++) {
int k = (int)(Math.random()*10 + 1);
System.out.print(k + " ");
sum += k;
}
System.out.print('\n' + "평균은 " + sum/10 + '\n' + sum);
}
}
Q8. 정수를 몇 개 저장할지 키보드로부터 개수를 입력받아 정수 배열을 생성하고, 이곳에 1에서 100까지 범위의 정수를 랜덤하게 삽입하라. 배열에는 같은 수가 없도록 하고 배열을 출력하라.
이하의 코드는 내가 짰는데 같은수가 없도록 하라는 요구를 구현 못했다.
package loop;
import java.util.Scanner;
public class game {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int arr[][];
System.out.print("정수 몇개??");
int a = sc.nextInt();
boolean fact = true;
int row = a/10;
int col = a%10;
arr = new int[row + 1][];
for(int i = 0; i < row; i++) {
arr[i] = new int[10];
}
arr[row] = new int[col];
for(int i = 0; i < row; i++) {
for(int j = 0; j < 10; j ++) {
arr[i][j] = (int)(Math.random()*100 + 1);
}
}
for(int i = 0; i < col; i++) {
arr[row][i] = (int)(Math.random()*100 + 1);
}
for(int i = 0; i < row; i++) {
for(int j = 0; j < 10; j ++) {
System.out.print(arr[i][j] + " ");
}
System.out.println();
}
for(int i = 0; i < col; i++) {
System.out.print(arr[row][i] + " ");
}
}
}
답을 찾아보니 한 줄로 치고 \n하면 될 일이였다. 하하하하하하 내 1시간 30분
이하의 코드는 https://security-nanglam.tistory.com/210 에서 가져왔다.
import java.util.Scanner;
public class java_study3_8 {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc = new Scanner(System.in);
int arr[];
int num;
System.out.print("정수 몇개? >> ");
num = sc.nextInt();
arr = new int[num];
for(int i=0; i<arr.length; i++) {
int tmp = (int)(Math.random()*100+1);
int chk = 0;
for(int j=0; j<arr.length; j++) {
if(tmp == arr[j]) {
chk=1;
break;
}
}
if(chk == 1) {
i--;
continue;
}
arr[i] = tmp;
}
for(int i=0; i<arr.length; i++) {
if(i%10 == 0 && i != 0) System.out.println();
System.out.print(arr[i] + " ");
}
sc.close();
}
}
Q9. 4*4의 2차원 배열을 만들고 1에서 10까지 범위의 정수를 랜덤하게 생성하여 정수 16개를 배열에 저장하고, 2차원 배열을 화면에 출력하라.
public class random {
public static void main(String[] args){
int arr[][] = new int[4][4];
for(int i =0; i <4; i++) {
for(int j = 0; j < 4; j++) {
int k = (int)(Math.random()*10+1);
arr[i][j] = k;
System.out.print( k + " ");
}
System.out.println();
}
}
}
Q10. 위의 문제에서 6개의 숫자에 0을 입력하라.
package loop;
public class game {
public static void main(String[] args){
int arr[][] = new int[4][4];
int a, b;
int count = 0;
for(int i =0; i <4; i++) {
for(int j = 0; j < 4; j++) {
arr[i][j] = (int)(Math.random()*10+1);
}
}
do {
count = 0;
for(int i =0; i <4; i++) {
for(int j = 0; j < 4; j++) {
if(arr[i][j] == 0)
count++;
}
}
if(count != 6) {
a = (int)(Math.random()*10+1) % 4;
b = (int)(Math.random()*10+1) % 4;
if(arr[a][b] != 0)
arr[a][b] = 0;
}
}while(count != 6);
for(int i =0; i <4; i++) {
for(int j = 0; j < 4; j++) {
System.out.print( arr[i][j] + " ");
}
System.out.println("");
}
}
}
Q11. 명령 프롬프트로받는 것
public class Average {
public static void main(String[] args){
int sum = 0;
for(int i = 0; i < args.length; i++) {
sum += Integer.parseInt(args[i]);
}
System.out.print(sum/args.length);
}
}
Q12. 위의 문제 중 정수를 제외한 문자를 입력해도 가능한 것을 구현해라
public class Add {
public static void main(String[] args){
int sum = 0;
int count = 0;
for(int i = 0; i < args.length; i++) {
try {
sum += Integer.parseInt(args[i]);
}
catch(NumberFormatException e) {
count++;
}
}
System.out.print(sum);
}
}
Q13. 반복문을 이용하여 369게임에서 박수를 쳐야 하는 경우를 순서대로 화면에 출력해보자. 1부터 시작하며 99까지만 한다.
public class game {
public static void main(String[] args) {
for(int i = 1; i<=100; i++) {
if(i/10 == 3 || i/10 == 6 || i/10 == 9 || i%10 == 3 || i%10 == 6 || i%10 == 9 ) {
System.out.print(i + " 박수 ");
if(i/10 == 3 || i/10 == 6 || i/10 == 9)
System.out.print("짝");
if(i%10 == 3 || i%10 == 6 || i%10 == 9)
System.out.print("짝");
System.out.println();
}
}
}
}
Q14. 과목과 점수가 짝을 이루도록 2개의 배열을 작성하라
package loop;
import java.util.Scanner;
public class game{
public static void main(String[] args) {
String course[] = {"Java", "C++", "HTML5", "컴퓨터구조", "안드로이드"};
int score[] = {95, 88, 76, 62, 55};
Scanner sc = new Scanner(System.in);
int find;
while(true) {
find = 0;
System.out.print("과목 이름>>");
String s = sc.next();
for(int i = 0; i < 5; i++) {
if(course[i].equals(s)) {
find = 1;
System.out.println(s + "의 점수는 " + score[i]);
}
}
if(s.equals("그만"))
break;
if(find == 0)
System.out.println("없는 과목입니다.");
}
}
}
Q15. 곱하는 계산을 구현하되 실수를 입력할시 안내문구를 띄우고 다시 입력할 수 있는 기능을 추가해라.
package loop;
import java.util.Scanner;
import java.util.InputMismatchException;
public class game{
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
while(true) {
System.out.print("곱하고자하는 두 수 입력>>");
try {
int a = sc.nextInt();
int b = sc.nextInt();
int result = a * b;
System.out.print(a + "*" + b + "=" + result);
break;
}
catch(InputMismatchException e) {
System.out.println("실수는 입력하면 안됩니다.");
sc.nextLine();
}
}
}
}
Q16. 컴퓨터와 독자 사이의 가위 바위 보 게임을 만들어보자. 예시는 다음 그림과 같다. 독자부터 먼저 시작한다. 독자가 가위 바위 보 중 하나를 입력하고 <Enter>키를 치면, 프로그램은 가위 바위 보 중에서 랜덤하게 하나를 선택하고 컴퓨터가 낸 것으로 한다. 독자가 입력한 값과 랜덤하게 선택한 값을 비교하여 누가 이겼는지 판단한다. 독자가 가위 바위 보 대신 "그만"을 입력하면 게임을 끝난다.
package loop;
import java.util.Scanner;
public class game{
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("컴퓨터와 가위 바위 보 게임을 합니다.");
String cs[] = {"가위", "바위", "보"};
while(true) {
System.out.print("가위 바위 보!>>");
String input = sc.next();
if(input.equals("그만")) {
System.out.print("게임을 종료합니다...");
break;
}
else {
int n = (int)(Math.random()*3);
if(input.equals(cs[n])) {
System.out.println("사용자 = " + input + " , 컴퓨터 = " + cs[n] +", 비겼습니다.");
}
if(input.equals("가위")){
if(cs[n].equals("바위")) {
System.out.println("사용자 = " + input + " , 컴퓨터 = " + cs[n] +", 컴퓨터가 이겼습니다.");
}
else if(cs[n].equals("보")) {
System.out.println("사용자 = " + input + " , 컴퓨터 = " + cs[n] +", 사용자가 이겼습니다.");
}
}
else if(input.equals("바위")){
if(cs[n].equals("보")) {
System.out.println("사용자 = " + input + " , 컴퓨터 = " + cs[n] +", 컴퓨터가 이겼습니다.");
}
else if(cs[n].equals("가위")) {
System.out.println("사용자 = " + input + " , 컴퓨터 = " + cs[n] +", 사용자가 이겼습니다.");
}
}
else if (input.equals("보")){
if(cs[n].equals("가위")) {
System.out.println("사용자 = " + input + " , 컴퓨터 = " + cs[n] +", 컴퓨터가 이겼습니다.");
}
else if(cs[n].equals("주먹")) {
System.out.println("사용자 = " + input + " , 컴퓨터 = " + cs[n] +", 사용자가 이겼습니다.");
}
}
else {
System.out.println("가위 바위 보 중 하나를 입력하세요.");
}
}
}
}
}
'java > 학교,기관' 카테고리의 다른 글
모듈과 패키지 개념, 자바 기본 패키지(프로그래밍 심화)(명품 JAVA Programming ) (0) | 2022.11.10 |
---|---|
상속(프로그래밍 심화)(명품 JAVA Programming ) (0) | 2022.10.22 |
클래스와 객체(프로그래밍 심화)(명품 JAVA Programming ) (0) | 2022.10.17 |
자바 기본 프로그래밍(프로그래밍 심화)(명품 JAVA Programming ) (0) | 2022.10.08 |
자바 시작(프로그래밍 심화)(명품 JAVA Programming ) (0) | 2022.10.03 |
댓글