Javaでマスターマインドを作成しているプログラミング初心者です。
Userからのinputを取得し、作成済みのString[]の全ての要素と比較したいです。
今考えているのが
①String[] にn個要素が入っている
②User inputを取得(inputの取得にはscannerを使用)
③inputとString[]のn個の要素と比較
④inputが要素のどれか1つとでも一致していれば新しい別のString[]に格納、どれとも一致しなければ警告メッセージを表示
②から④を一定回数繰り返す。
というプロセスなのですが、コードを書いてみても思う結果が得られません。
以下そのコードです。作成段階なので完成していません。
Java
1public static void main(String[] args){ 2 Scanner scan = new Scanner(System.in); 3 4 boolean condition = true; 5 int numberPeg = 0; 6 String [] orderPeg = null; 7 int numberColour = 0; 8 String[] nameColour=null; 9 10 System.out.println("Enter the number of pegs."); 11 try{ 12 while(condition){ 13 numberPeg = scan.nextInt(); 14 if(numberPeg<9){ 15 orderPeg = new String [numberPeg]; 16 condition=false; 17 } 18 else{System.err.println("Enter the number between 3-8.");} 19 } 20 } 21 catch(InputMismatchException ime){System.err.println("Input valid argument.");} 22 condition=true; 23 24 System.out.println("Enter the number of colours."); 25 try{ 26 while(condition){ 27 numberColour = scan.nextInt(); 28 if(numberColour<=numberPeg){ 29 nameColour = new String [numberColour]; 30 condition=false; 31 } 32 else{ 33 System.err.println("Enter appropriate number."); 34 } 35 } 36 } 37 catch(InputMismatchException ime){System.err.println("Input valid argument.");} 38 condition=true; 39 40 System.out.println("Enter colours."); 41 try{ 42 try{ 43 int counter=0; 44 while(counter<nameColour.length){ 45 String inputColour = scan.next(); 46 if(inputColour.equals("blue")||inputColour.equals("green")||inputColour.equals("orange")||inputColour.equals("purple")){ 47 nameColour[counter]=inputColour; 48 counter++; 49 } 50 else{System.err.println("Colours must be blue, green, orange or purple.");} 51 } 52 } 53 catch(NullPointerException npe){} 54 } 55 catch(InputMismatchException ime){System.err.println("Input valid argument.");} 56 57 //ここが問題の箇所です 58 System.out.println("Enter the colour of the order."); 59 try{ 60 try{ 61 int counter=0; 62 while(counter<numberPeg){ 63 String inputColour = scan.next(); 64//ここで比較する際に、nameColourの0番目の要素だけでなく、全ての要素と比較して、inputColourがnameColourに含まれているのか確かめたいです。 65 if(inputColour.contains(nameColour[counter])){ 66 orderPeg[counter]=inputColour; 67 counter++; 68 } 69 else{System.err.println("Must be the same colour you chose before.");} 70 } 71 } 72 catch(NullPointerException npe){} 73 } 74 catch(InputMismatchException ime){System.err.println("Input valid argument.");} 75 76 System.out.println("GAME START"); 77 System.out.println("The number of pegs are "+numberPeg); 78 79}
このコードでは、inputColourがnameColourと全く同じでなければ、警告メッセージがプリントされました。
アドバイスをお願いします。
回答2件
あなたの回答
tips
プレビュー