반응형
4. 자바에서는 scanner로 문자 하나를 입력받을 수 없다. 따라서 문자열로 입력받은 후, 그 문자열의 첫번째 인덱스를 s.charAt(0)과 같이 얻어낸뒤, char타입에 저장하면 된다. 아스키코드값('0' = 48, 'A' = 65, 'a' = 97) 외워두면 편하다.
import java.util.Scanner;
public class WhileTest {
public static void main(String[] args) {
System.out.print("소문자 알파벳 하나를 입력하시오>>");
Scanner scanner = new Scanner(System.in);
String s = scanner.nextLine();
char end = s.charAt(0);
for(char i = end;i>='a';i--) {
for(char j ='a';j<=i;j++) {
System.out.print(j);
}
System.out.println();
}
scanner.close();
}
}
8. 중복된 숫자가 발생할 경우 난수를 다시 생성하는 과정이 생각보다 복잡하다. 다른 블로그 코드보다 쉽게 작성하였다.
import java.util.Scanner;
import java.util.InputMismatchException;
import java.util.Random;
public class App {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int count = 0;
while (true) {
System.out.print("정수 몇개?");
count = scanner.nextInt();
if (count >= 1 && count < 100)
break;
else
System.out.println("1이상 99이하의 개수를 입력해주세요!");
}
int[] intArray = new int[count];
for (int i = 0; i < intArray.length; i++) {
if (i % 10 == 0)
System.out.println();
while (true) {
int randomNum = (int) (Math.random() * 100 + 1);
boolean isDuplicated = false;
for(int j = 0;j<i;j++) {
if(randomNum == intArray[j]) {
isDuplicated =true;
break;
}
}
if(!isDuplicated) {
intArray[i] = randomNum;
break;
}
}
System.out.print(intArray[i] + " ");
}
scanner.close();
}
}
10. 행과 열의 수를 랜덤으로 정하고, intArray[i][j] 가 0일때만 난수 값을 넣고 break를 해서 while문을 빠져나오게 하였다.
import java.util.Scanner;
import java.util.InputMismatchException;
import java.util.Random;
public class App {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int[][] intArray = new int[4][4];
int randNumOfRow = 0;
int randNumOfColumn = 0;
for (int i = 0; i < 10; i++) {
while (true) {
randNumOfRow = (int) (Math.random() * 4);
randNumOfColumn = (int) (Math.random() * 4);
if (intArray[randNumOfRow][randNumOfColumn] == 0) {
int randNum = (int) (Math.random() * 10 + 1);
intArray[randNumOfRow][randNumOfColumn] = randNum;
break;
}
}
}
for (int[] row : intArray) {
for (int k : row) {
System.out.print(k + "\t");
}
System.out.println();
}
scanner.close();
}
}
13. 3,6,9 게임에 반복문을 추가한것이다. 2장의 실습문제에 비슷한게 있었던것 같기도
import java.util.Scanner;
public class Add {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
for(int i =1;i<100;i++) {
int digitOf1 = i%10;
int digitOf10 = i/10;
int clapCount = 0;
if(digitOf1 != 0 && digitOf1 % 3 ==0)
clapCount++;
if(digitOf10 != 0 && digitOf10%3 ==0)
clapCount++;
if(clapCount == 1)
System.out.println(i+" 박수 짝");
else if (clapCount ==2)
System.out.println(i + " 박수 짝짝");
}
scanner.close();
}
}
14. 두개의 배열의 같은 인덱스가 같은 항목을 나타내고 있다. for - each문을 쓰려다가, 특정 인덱스의 숫자가 필요해서 일반적인 for문으로 바꾸었다.
import java.util.Scanner;
public class Add {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String course[] = { "Java", "C++", "HTML5", "컴퓨터구조", "안드로이드" };
int score[] = { 95, 88, 76, 62, 55 };
while (true) {
System.out.print("과목 이름>>");
String input = scanner.nextLine();
if (input.equals("그만"))
break;
boolean existOfSubject = false;
for(int i =0;i<course.length;i++) {
if(course[i].equals(input))
{System.out.println(course[i]+"의 점수는 "+score[i]);
existOfSubject = true;
}
}
if(!existOfSubject)
System.out.println("없는 과목입니다.");
}
scanner.close();
}
}
16. 음.. 중간에 반복되는 부분이 있어서 그걸 함수로 고쳤다.
import java.util.Scanner;
import java.util.InputMismatchException;
public class Add {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String str[] = {"가위","바위","보"};
System.out.println("컴퓨터와 가위 바위 보 게임을 합니다.");
while(true) {
System.out.print("가위 바위 보!>>");
String hand = scanner.nextLine();
if(hand.equals("그만")) {
System.out.println("게임이 종료되었습니다.");
break;
}
if(!hand.equals("가위")&&!hand.equals("바위")&&!hand.equals("보")) {
System.out.println("잘못된 입력입니다. 가위, 바위, 보 중 하나를 입력하세요.");
continue;}
int randNum = (int)(Math.random()*3); // 0, 1 ,2
String computerHand = str[randNum];
String status = getGameStatus(hand,computerHand);
System.out.println("사용자 = "+hand+" , 컴퓨터 = "+str[randNum]+", "+status);
}
scanner.close();
}
public static String getGameStatus(String userHand, String computerHand) {
if(userHand.equals(computerHand))
return "비겼습니다.";
else if((userHand.equals("가위")&&computerHand.equals("보")) ||
(userHand.equals("바위")&&computerHand.equals("가위")) ||
(userHand.equals("보")&&computerHand.equals("바위"))
)
return "사용자가 이겼습니다.";
else
return "컴퓨터가 이겼습니다.";
}
}
반응형
댓글