1.다음 프로그램에 대해 물음에 답하라?
int sum = 0 ; i = 0;
while( i < 100){
sum = sum + i;
i = i + 2;
}
System.out.println(sum);
(1) 무엇을 계산하는 코드이며 실행 결과 출력되는 내용은?
답: Sum의 합을 계산하는 코드이다.
(2) 위의 코드를 main 메소드로 만들고 WhileTest 클래스로 완성하라.
public class WhileTest {
public static void main(String[] args) {
int sum =0; int i =0;
while (i<100){
sum= sum+i;
i = i+2;
}
System.out.println(sum);
}
}
(3) for문을 이용하여 동일하게 실행되는 ForTest 클래스를 작성하라.
public class WhileTest {
public static void main(String[] args) {
int sum =0; int i =0;
for(i=0;i<100;i=i+2){
sum = sum +i;
}
System.out.println(sum);
}
}
(4) do - while 문을 이용하여 동일하게 실행되는 DoWhileTest 클래스를 작성하라.
public class DoWhileTest {
public static void main(String[] args) {
int i=0; int sum =0;
do {
sum = sum + i;
i = i + 2;
}while (i<100);
System.out.println(sum);
}
}
실습문제 2 . 다음 2차원 배열 n을 출력하는 프로그램을 작성하라.
int n [][] = {{1} , {1 , 2, 3} , { 1 } , { 1,2,3,4} { 1, 2}};
public class Array {
public static void main(String[] args) {
int n[][] = {{1},{1,2,3},{1},{1,2,3,4},{1,2,}};
for(int i=0;i<n.length;i++){
for(int j=0;j<n[i].length;j++){
System.out.print(n[i][j]);
}
System.out.println();
}
}
}
public class ex12 {
public static void main(String[] args) {
int n[][] = {{1}, {1, 2, 3}, {1}, {1, 2, 3, 4}, {1, 2}};
for(int i=0; i<n.length; i++) {
for(int j=0; j<n[i].length; j++) {
System.out.print(n[i][j]+ " ");
}
System.out.println();
}
}
}
실습문제 3번
Scanner를 이용하여 정수를 입력받고 다음과 같이 *을 출력하는 프로그램을 작성하라.
다음은 5를 입력받았을 경우이다.
정수를 입력하시오. >> 5
*****
****
***
**
*
이중포문으로 사용해도 되지만 더 쉽게 사용하는 방법이 있다.
repaeat함수를 쓰면 지정한 만큼 반복되기때문에 reapeat 함수를 이용해보자.
public class Array {
public static void main(String[] args) {
String name = "*";
Scanner sc = new Scanner(System.in);
System.out.println("정수를 입력하시오");
int number = sc.nextInt();
for(int i=0;i<number;){
try {
System.out.printf(name.repeat(number--));
System.out.println();
i--;
}catch (Exception e){
return;
}
}
}
}
이중 포문으로 사용하는 코드는
public class java_study3_4 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("정수를 입력하세요");
int num = sc.nextInt();
for (int i = 0; i < num; i++) {
for (int j = 0; j < num-i; j++) { //num-i만큼 돌려준다 반복문이 돌수록 5,4,3,2,1로 뺴짐
System.out.print("*"); // *을 출력한다.
}
System.out.println();
}
}
}
실습문제 4번
Scaaner를 이용하여 소문자 알파벳을 하나 입력받고 다음과 같이 출력하는 프로그램을 작성하라.
다음은 e를 입력받았을 경우이다.
소문자 알파벳 하나를 입력하시오 >> e
abcde
abcd
abc
ab
a
package 예제파일1번;
//명품 자바 2장 실습문제 6번
import java.util.HashMap;
import java.util.Iterator;
import java.util.Scanner;
public class java_study3_4 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("소문자 알바펫 하나를 입력하시오 >>");
String name = sc.nextLine();
char c = name.charAt(0);
for (int i = 0; i <= c - 'a'; i++) { // e는 아스키코드로 101임. a는 97이기때문에 0~4까지 반복
for (char j = 'a'; j <= c - i; j++) {//j를 a에 대입해줌으로 j=97이된다. 97='a'를 가르킴
System.out.print(j);
}
System.out.println();
}
}
}
e는 아스키코드로 101입니다. a는 아스키코드로 97이기 때문에 101 - 97을 하면 4가 나오죠
즉 i는 0~4까지 반복하라는 뜻이 됩니다.
j에 char 타입으로 문자 'a'를 넣었습니다 a는 97입니다. 97(j) <= 101(c) - 0(i)가 됨으로 97 <= 101이 됩니다.
출력문에 j를 넣으면 j는 97임으로 a를 나오게 합니다.
이렇게 5번을 반복하기 때문에 abcde가 되고
다음 반복문으로 넘어갈 때는 i = 1이 되기때문에 0~4 => 0~3반복으로 바뀝니다.
실습문제 5번
양의 정수를 10개 입력받아 배열에 저장하고 , 배열에 있는 정수 중에서 3의 배수만
출력하는 프로그램을 작성하라.
public class java_study3_4 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int[] arr = new int[10];
for(int i=0;i<arr.length;i++){
System.out.println("양의 정수 10개를 입력하세요 >>"+i+1+"번째 입력입니다.");
arr[i]=sc.nextInt();
}
for(int i=0;i<arr.length;i++){
if(arr[i]%3==0){
System.out.println("양의 정수는 :"+arr[i]+"입니다");
}
}
배열과 반복문을 이용하여 프로그램을 작성해보자. 키보드에서 정수로 된 돈의 액수를 입력받아
오만 원권 , 만 원권 , 천 원권 500원짜리 동전 , 100원짜리 동전 , 50원 짜리 동전 10원짜리 동전
1원짜리 동전이 각 몇 개로 변환되는지 예시와 같이 출력하라. 이때 반드시 다음 배열을 이용하고
반복문으로 작성하라.
금액을 입력하시오 >> 65123
50000원 짜리 : 1개
10000원짜리 : 1개
1000원 짜리 : 5개
100원 짜리 1개
10원짜리 2개
1원짜리 3개
package 예제파일1번;
//명품 자바 2장 실습문제 6번
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Scanner;
import java.util.concurrent.SynchronousQueue;
public class java_study3_4 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int[] unit = {50000,10000,1000,500,100,50,10,1};
System.out.println("금액을 입력하시오 >>");
int number = sc.nextInt();
for(int i=0;i<unit.length;i++){
System.out.println(unit[i]+"짜리 :"+number/unit[i]+"개");
number=number%unit[i];
}
}
}
실습문제 7번 정수를 10개 저장하는 배열을 만들고 1에서 10까지 범우위 정수를 랜덤하게 생성해
배열에 저장하라, 그리고 배열에 든 숫자들과 평균을 출력하라.
랜덤한 정수들 : 10 , 5 , 2 , 9 , 1 , 4 , 1 , 5 , 1 , 5
package 예제파일1번;
//명품 자바 2장 실습문제 6번
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Scanner;
import java.util.concurrent.SynchronousQueue;
public class java_study3_4 {
public static void main(String[] args) {
int avg=0;
Scanner sc = new Scanner(System.in);
int[] unit = {10,5,2,9,1,4,1,5,1,5};
System.out.println("랜덤한 정수들");
for(int i=0;i<unit.length;i++){
avg=unit[i]+avg;
}
avg=avg/unit.length;
System.out.println("평균은 :"+(double)avg);
}
}
실습문제 8번
정수를 몇개 저장할지 키보드로부터 개수를 입력받아(100보다 작은 개수)정수 배열을 생성하고
이곳에서 1에서 100까지 범위의 정수를 랜덤하게 삽입하라. 배열에는 같은 수가 없도록 하고 배열을 출력하라.
package 예제파일1번;
import java.util.Scanner;
public class java_study3_8 {
public static void main(String[] args) {
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();
}
}
10번
import java.util.Scanner;
public class main{
public static void main(String[] args){
Scanner in = new Scanner(System.in);
int arr [][] = new int[4][4];
int result = 0;
while(result < 10){
int p1 = (int)(Math.random()*4);
int p2 = (int)(Math.random()*4);
if(arr[p1][p2] == 0){
arr[p1][p2] = (int)(Math.random()*10 + 1);
result++;
}
}
for(int i = 0; i < 4; i++){
for(int j = 0; j < 4; j++){
System.out.print(arr[i][j] + " ");
}
System.out.println();
}
}
}
10번
11번
import java.util.Scanner;
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.println(sum / args.length);
}
}
12번
import java.util.Scanner;
public class main{
public static void main(String[] args){
int sum = 0;
for(int i = 0; i < args.length; i++){
try{
sum += Integer.parseInt(args[i]);
}
catch (NumberFormatException e){
continue;
}
}
System.out.println(sum / args.length);
}
}
13번
import java.util.Scanner;
public class main{
public static void main(String[] args){
for(int i = 1; i< 100; i++){
int t1 = i % 10;
int t2 = i / 10;
if((t1 == 3 || t1 == 6 || t1 == 9) && (t2 == 3 || t2 == 6 || t2 == 9)){
System.out.println(i + " 박수 짝짝");
}
else if(t1 == 3 || t1 == 6 || t1 == 9 || t2 == 3 || t2 == 6 || t2 == 9){
System.out.println((i + " 박수 짝"));
}
}
}
}
13번
14번
package 예제파일1번;
import java.util.Scanner;
public class java_study3_8 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String course[] = {"Java", "C++", "HTML5", "컴퓨터구조", "안드로이드"};
int score[] = {95, 88, 76, 62, 55};
while (true) {
System.out.println("과목이름 >>");
String name = sc.nextLine();
if (name.equals("그만")) break;
int count = 0;
for (int i = 0; i < course.length; i++) {
if (course[i].equals(name))
System.out.println(course[i]+"의 점수는 :"+score[i]);
count=1;
if(count==0){
System.out.println("없는 과목입니다.");
}
}
}
}
}
14번
컴퓨터와 독자 사이의 가위 바위 보 게임을 만들어보자. 예시는 다음 그림과 같다.
독자부터 먼저 시작한다. 독자가 가위 바위 보 중 하나를 입력하고 <Enter>키를 치면,
프로그램은 가위 바위 보 중에서 랜덤하게 하나를 선택하고 컴퓨터가 낸 것으로 한다.
독자가 입력한 값과 랜덤하게 샌턱한 값을 비교하여 누가 이겼는지 판단한다. 독자가 가위 바위 보 대신
"그만"을 입력하면 게임은 끝난다.
package 예제파일1번;
import java.util.Scanner;
public class java_study3_8 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String[] array = {"가위","바위","보"};
System.out.println("컴퓨터와 가위 바위 보 게임을 합니다.");
while (true){
System.out.println("가위 바위 보!");
String name = sc.nextLine();
String Computer = array[(int) (Math.random()*3)];
if(name.equals("그만")) break;
switch (Computer){
case "가위":
if (name.equals("가위")) System.out.println("사용자 :"+name+" "+"컴퓨터 :"+Computer+"로 사용자는 비겼습니다");
if (name.equals("보")) System.out.println("사용자 :"+name+" "+"컴퓨터 :"+Computer+"로 사용자는 이겼습니다");
if (name.equals("바위")) System.out.println("사용자 :"+name+" "+"컴퓨터 :"+Computer+"로 사용자는 이겼습니다");
break;
case "바위":
if (name.equals("보")) System.out.println("사용자 :"+name+" "+"컴퓨터 :"+Computer+"로 사용자는 졌습니다");
if (name.equals("바위")) System.out.println("사용자 :"+name+" "+"컴퓨터 :"+Computer+"로 사용자는 비겼습니다");
if (name.equals("가위")) System.out.println("사용자 :"+name+" "+"컴퓨터 :"+Computer+"로 사용자는 이겼습니다");
break;
case "보":
if (name.equals("바위")) System.out.println("사용자 :"+name+" "+"컴퓨터 :"+Computer+"로 사용자는 이겼습니다");
if (name.equals("보")) System.out.println("사용자 :"+name+" "+"컴퓨터 :"+Computer+"로 사용자는 비겼습니다");
if (name.equals("보")) System.out.println("사용자 :"+name+" "+"컴퓨터 :"+Computer+"로 사용자는 졌습니다");
break;
}
}
}
}
'명품 자바 문제' 카테고리의 다른 글
[명품 자바] 제 4장 클래스와 객체 실습문제 (1) | 2023.01.06 |
---|---|
[명품 자바 3장] 카드 번호 맞추기 게임 (1) | 2023.01.06 |
[명품 자바 2장] Open Challenge 가위바위보 게임 (1) | 2022.12.23 |
[명품 자바] 2장 실습문제 7~12번까지 (1) | 2022.12.23 |
명품자바 2장 실습문제 [답지,풀이] (2) | 2022.12.22 |