프로그래밍 언어/JAVA

<Java>자바의 정석 5장 13번 toCharArray(), 단어 위치섞기

창조적생각 2021. 7. 2. 09:57

단어의 글자위치를 섞어서 보여주고 원래의 단어를 맞추는 프로그램을 짜라.

 

String[] word = {"television", "computer", "mouse", "phone"};

 

[결과]

 

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

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

Q3. emuso의 정답을 입력하세요.>omuso
틀렷습니다. 

Q4. ohepn의 정답을 입력하세요.>phone
맞았습니다. 

 

[풀이]

import java.util.Scanner;
public class practice5_13 {

public static void main(String[] args) {
// TODO Auto-generated method stub
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(); /* to CharArray() 함수를 사용하면 words 배열안의 문자열을 하나하나씩 문자로 풀어줍니다.

question[] = {t,e,l,e,v,i,s,i,o,n,c,o,m,p,u,t,e,r,m,o,u,s,e,p,h,o,n,e}

*/

for(int j = 0; j <question.length;j++) {

int idx = (int)(Math.random()*question.length);
char tmp = question[i];
question[i] = question[idx];
question[idx] = tmp;

// 문자열을 랜덤으로 섞기 위해서 사용합니다.

}

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

String answer = scanner.nextLine();
if(words[i].equals(answer.trim()))

System.out.printf("맞았습니다.%n%n");

else

System.out.printf("틀렸습니다. %n%n");

}

}

}

 

 

728x90