/**
* 随机产生四个不相同的字符,然后输入4个字符(一串),与这四个随机字符比
* 较,不相同则记录其位置,重新猜测其值并输入,直到完全猜对,最后输出匹配的个数。
*/
package package1;
import java.util.Random;
import java.util.Scanner;
/**
* random 4 chars as test codes,make it single with no as the same.
* system.out it(can't see).and then enter 4 chars,test if they are matches.
*/
public class matchesDemo {
public static void main(String[] args) {
char[] testChars = new char[4];
//receive and print testChars.
testChars = randomChars();
System.out.println("the testChars code:");
for(int i = 0;i<testChars.length;i++){
System.out.print(testChars[i]+" ");
}
System.out.println();
compareChars(testChars);
}
//build up a method,return 4 chars as testChar without the same.
public static char[] randomChars(){
char letters[] = {'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'};
//random 4 numbers from 0 to 26 as the index of charArray in letters.
char charArray[] = new char[4];
for(int i=0;i<4;i++){
int randomNum = new Random().nextInt(26);
charArray[i] = letters[randomNum];
}
/**
* make sure that it don't to be the same:
* from 0 to 4,every char at this index,ever same to the every char behind itself,random a new number as its index in letters.
* as while,retest the char(0-4) with its after char.
*/
boolean flag;
for(int j=0;j<4;j++){
flag = false;
do{
for(int k=j+1;k<4;k++){
if(charArray[j]==charArray[k]){
flag = true;
charArray[k] = letters[new Random().nextInt(26)];
}
}
}while(flag);
}
return charArray;
}
//build up a method,scanner 4 chars to be your chars,and matches them with testChars,print how much they matches.
public static void compareChars(char[] testChars){
Scanner in = new Scanner(System.in);
char[] myChars = new char[4];
System.out.println("enter your 4 chars as a string:");
String s = in.nextLine();
for(int i=0;i<testChars.length;i++){
myChars[i] = s.charAt(i);
}
int matchesNum = 0;
for(int j=0;j<testChars.length;j++){
if(myChars[j]==testChars[j]){
matchesNum++;
}else{
System.out.println("the index of "+j+" is not matches!");
System.out.println("enter again:");
myChars[j] = new Scanner(System.in).nextLine().charAt(0);
j--;
}
}
System.out.println("the total numbers that matches:"+matchesNum);
}
}
结果示例(the result):
the testChars code:
j f e b
enter your 4 chars as a string:
jbeb
the index of 1 is not matches!
enter again:
f
the total numbers that matches:4