java
import java.io.Console; import java.util.Scanner; public class sampul1{ public static void main(String[] args) { //ゲーム説明 System.out.print("このゲームは3桁の数字を当てるゲームです"); System.out.println("正解するまでの回数が少なかった方が勝利です"); System.out.println("数字と桁が両方合っていればHit,数字のみならばBlowと表示されます"); //数字設定 Scanner sc=new Scanner(System.in); Console cons=System.console(); if(cons==null) { System.out.println("cons==null"); return; } String name1="player1"; System.out.println(name1+"さん3桁の数字を設定してください"); while(true) { boolean number=true; char[] answer1=cons.readPassword(); String input=new String(answer1); char []a=input.toCharArray(); int il=input.length(); for(int i=0; i<3; i++) { for(int j=i+1; j<3; j++) { if(a[i]==a[j]||il!=3) { number=false; } } } if(number==false) { System.out.println("数字は重複せず、3桁です"); continue; } String name2="player2"; System.out.println(name2+"さん3桁の数字を設定してください"); while(true) { boolean num=true; char[] answer2=cons.readPassword(); String reinput=new String(answer2); char[]b=reinput.toCharArray(); int rl=reinput.length(); for(int i=0; i<3; i++) { for(int j=i+1; j<3; j++) { if(b[i]==b[j]||rl!=3) { num=false; } } } if(num==false) { System.out.println("数字は重複せず、3桁です"); continue; } //player1 System.out.println(name1+"さん相手の3桁を予想してください"); int count=1; while(true) { boolean nu=true; String c=sc.nextLine(); char[] d=c.toCharArray(); int cl=c.length(); for(int i=0; i<3; i++) { for(int j=i+1; j<3; j++) { if(d[i]==d[j]||cl!=3) { nu=false; } } } if(nu==false) { System.out.println("数字は重複せず、3桁です"); continue; } int hit=0, blow=0; for(int i=0; i<3; i++) { if(d[i]==b[i]) { hit++; }else{ for(int j=0; j<3; j++) { if(d[i]==b[j]) { blow++; } } } } if(hit!=3) { System.out.println(hit+"Hit "+blow+"Blow"); count++; } if(hit==3) { System.out.println(name1+"さんは"+count+"回目で正解しました。"); break; } } //player2 System.out.println(name2+"さん相手の3桁の数字を予想してください"); int recount=1; while(true) { boolean n=true; String e=sc.nextLine(); char[] f=e.toCharArray(); int el=e.length(); for(int i=0; i<3; i++) { for(int j=i+1; j<3; j++) { if(f[i]==f[j]||el!=3) { n=false; } } } if(n==false) { System.out.println("数字は重複せず、3桁です"); continue; } int ahit=0, ablow=0; for(int i=0; i<3; i++) { if(f[i]==a[i]) { ahit++; }else{ for(int j=0; j<3; j++) { if(f[i]==a[j]) { ablow++; } } } } if(ahit!=3) { System.out.println(ahit+"Hit "+ablow+"Blow"); recount++; } if(ahit==3) { System.out.println(name2+"さんは"+recount+"回目で正解しました。"); if(count==recount) { System.out.println("引き分けです"); } if(count<recount) { System.out.println(name1+"さんの勝利です!"); } if(count>recount) { System.out.println(name2+"さんの勝利です!"); } break; } } } } } }
java初心者です。一応完成形?に近い形まで出来ました。
①readPassword以外で自分で数字を設定できてかつ非表示にする方法はないのでしょうか?(readPasswordはターミナルでしか実行できなくなるので。)
②このコードは同じ構文を繰り返していますが、他にもっと短縮簡素化できるコードは何かありますか?
まだ回答がついていません
会員登録して回答してみよう