0

ユーザーが入力する色に応じて、フルカラーアウト(大文字と小文字を区別しない)または色の最初の文字である文字(大文字と小文字を区別しない)のいずれかを入力して、ユーザーが2つの色から選択できるようにするプログラムに苦労していますもう一方を別の変数に自動的に割り当てます。私の 2 つのオプションは青と緑です。青は正常に動作しているようですが、緑または g を入力すると、メソッドは新しい入力を求め続けます。これは、色の割り当てを処理する私のプログラムの抜粋です。

import java.util.*;
public class Test{
  public static Scanner in = new Scanner (System.in);
  public static void main(String []args){

    System.out.println("Chose and enter one of the following colors (green or blue): ");
    String color = in.next();
    boolean b = false;
    while(!b){
      if(matchesChoice(color, "blue")){
        String circle = "blue";
        String walk = "green";
        b = true;
      }
      else if(matchesChoice(color, "green")){
        String circle = "green";
        String walk = "blue";
        b = true;
      }
    }     

  }
  public static boolean matchesChoice(String color, String choice){
    String a= color;
    String c = choice;
    boolean b =false;
    while(!a.equalsIgnoreCase(c.substring(0,1)) && !a.equalsIgnoreCase(c)){
      System.out.println("Invalid. Please pick green or blue: ");
      a = in.next();
    }
    b = true;
    return b;

  }

}

基本的に、ユーザーが色の選択肢の 1 つを選択することを保証する while ループと、ユーザーによる文字列入力が質問の文字列オプションと一致するかどうかを判断するメソッドを作成しています。

4

1 に答える 1

1

else if(matchesChoice(color, "green"))到達できません。orを入力するmatchesChoice(color, "blue")とメソッドが呼び出されるため、常にorと比較されます。その後、そのメソッド内でorを入力し続けるため、ループし続けます。ggreenbblueggreen

matchesChoice を返すtruefalsecolor一致する場合は次のようにしchoiceます。

public static boolean matchesChoice(String color, String choice){
    String a= color;
    String c = choice;
    if (a.equalsIgnoreCase(c.substring(0,1)) || a.equalsIgnoreCase(c)) {
        return true;
    }
    return false;
}

次に、main の while ループ内にユーザー入力のスキャンを追加します。

boolean b = false;
System.out.println("Chose and enter one of the following colors (green or blue): ");
while(!b){
    String color = in.next();
    if(matchesChoice(color, "blue")){
        String circle = "blue";
        String walk = "green";
        b = true;
    }
    else if(matchesChoice(color, "green")){
        String circle = "green";
        String walk = "blue";
        b = true;
    }
    else {
        System.out.println("Invalid. Please pick green or blue: ");
    }
}
于 2016-11-15T02:34:11.790 に答える