[英]How do you test the value of charAt(0)?
因此,我正在編寫一個代碼,詢問用戶是否希望被推薦為新寵物。 我給他們一個消息對話框,要求他們輸入Y表示“是”,輸入N表示“否”。這是我的代碼,到目前為止,我沒有得到某些提示。 最大的問題是如何測試他們輸入的值是Y還是N。他們給出的答案可以是小寫或大寫。 我該如何編碼?
public static void aPet()
{
char answer;
String newPet;
newPet = JOptionPane.showInputDialog(null,"Would you like to recommend another pet?(Y), or Stop (N)","Another Recommendation?", JOptionPane.QUESTION_MESSAGE);
answer = newPet.charAt(0);
if (answer == y || answer == Y)
{
//methods to recommend pet
}
if (answer == n || answer == N)
{
System.exit(-1);
}
}
您需要使用實際的字符文字,而不僅僅是字母:
if (answer == 'y' || answer == 'Y')
在代碼中用單引號將字母引起來來表示字符(它們也可以用其他方式表示,但這是最簡單的)。
您可以在《 Java教程》>“ 原始數據類型”中閱讀有關此內容的內容,其中包括:
始終對字符文字使用“單引號”,對於字符串文字始終使用“雙引號”。
您缺少值'y'
和'n'
單引號:
嘗試這個:
char answer = newPet.charAt(0);
if('y' == answer || 'Y' == answer) {
// recommend pet
} else {
// exit
}
要么
已編輯
if(newPet.matches("y|Y")) {
// recommend pet
} else {
// exit
}
要么
if("y".equalsIgnoreCase(newPet)) {
// recommend pet
} else {
// exit
}
您可以像這樣使用Character#toUpperCase()
:
if (Character.toUpperCase(answer) == 'Y')
{
//methods to recommend pet
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.