close
開發平台:
Eclipse。
概要:
因為有朋友問我幾A幾B的問題要我幫他degub,然後因為我到現在還不知道幾A幾B要如何判斷,所以趁這個機會順便學習幾A幾B,並且寫成程式碼。
操作方法:
系統會自己產生4位數的數字,請輸入4位數,系統會告訴你現在答案是幾A幾B。
程式碼:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.Scanner; | |
import java.util.Arrays; | |
class main{ | |
public static void main(String args[]){ | |
Scanner sc=new Scanner(System.in); | |
String computerGuess=""; | |
for(int i=0;i<4;i++) computerGuess+=(int)(Math.random()*10); //電腦自行產生4位數的亂數 | |
//System.out.println("random: "+computerGuess); | |
while(true){ | |
int A=0,B=0; | |
boolean check[]=new boolean[4]; //紀錄每個位數是否檢查過 | |
Arrays.fill(check, false); | |
String guess=sc.next(); //使用者輸入數字 | |
//檢查有幾A | |
for(int i=0;i<4;i++){ | |
if(computerGuess.charAt(i)==guess.charAt(i)){ | |
A++; | |
check[i]=true; | |
} | |
} | |
//檢查有幾B | |
for(int i=0;i<4;i++){ | |
for(int j=0;j<4;j++){ | |
if(!check[j] && computerGuess.charAt(j)==guess.charAt(i)){ | |
B++; | |
check[j]=true; | |
break; | |
} | |
} | |
} | |
//Output | |
if(A==4){ | |
System.out.println("Correct"); | |
break; | |
} | |
else{ | |
System.out.println(A+"A"+B+"B"); | |
} | |
} | |
} | |
} |
文章標籤
全站熱搜