2016-11-15 45 views
0

我正在努力使用戶可以通過輸入全色(不區分大小寫)或是顏色的第一個字母(不區分大小寫)的字符,根據顏色的不同,使用戶在兩種顏色之間進行選擇他們鍵入它會自動分配另一個變量。我的兩個選項是藍色和綠色,藍色似乎工作正常,但是當我輸入綠色或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; 

    } 

} 

我基本上創建一個while循環,從而確保了用戶選擇的顏色的選擇,並確定由用戶輸入的字符串是否爲問題的字符串選項相匹配的方法的一個。

+0

因爲你的代碼流不正確,否則如果(matchesChoice(顏色,「綠色」))'不可及,直到你輸入「藍色」或「b」 – Jerry06

+0

@ Jerry06你的意思是輸入藍色或b必須達到綠色? –

回答

1

else if(matchesChoice(color, "green"))無法訪問。當您輸入g或​​時,將調用matchesChoice(color, "blue")方法,因此它總是將其與bblue進行比較。然後在該方法中,它繼續循環,因爲您繼續輸入g或​​。

只要有matchesChoice返回truefalse如果color比賽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; 
} 

然後添加掃描用戶輸入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: "); 
    } 
} 
+0

我現在看到了這個錯誤。我已經將此應用於我的代碼,並且該程序正在工作。 –