簡體   English   中英

如果語句字符串始終打印

[英]if statement string always prints

do{
System.out.println("Would you like to enter another number? (y/n)");
restart = console.next().charAt(0);
if (!(restart=='y')||!(restart=='n')||!(restart=='N')||!(restart=='Y'))
{
System.out.println("You entered something other than the letters (y) or (n).");
}
else if (restart=='n'||restart=='N')
   {System.out.println("Goodbye.");}
}
while (!(restart=='y')||!(restart=='n')||!(restart=='N')||!(restart=='Y'));}
            while (restart=='y'||restart=='Y');}}

我希望用戶輸入大寫或小寫的y或n,如果它的y然后重新啟動運行良好的程序,然后我開始添加一些東西以捕獲不是ay或n的任何東西。 我希望大寫或小寫字母n顯示再見,並且什么也沒有發生,除y或n之外的其他任何內容再次要求輸入y或n,直到獲得corect輸入為止,它始終顯示您輸入的內容不是...消息和反復詢問ud是否要輸入其他號碼

您可能更喜歡的另一種選擇是編寫

while("YyNn".indexOf(restart) == -1)

這意味着“如果在"YyNn"找不到restart則再次循環”。

替換|| &&使用時! -否則您的條件永遠都是正確的。 restart總是不是Y或N,有時兩者都是。

這個

if (!(restart=='y')||!(restart=='n')||!(restart=='N')||!(restart=='Y'))

是相同的

if ((restart!='y')||(restart!='n')||(restart!='N')||(restart!='Y'))

所以你可能想要

if(!((restart=='y')||(restart=='n')||(restart=='N')||(restart=='Y')))

這和

if ((restart!='y')&&(restart!='n')&&(restart!='N')&&(restart!='Y'))

您還可以通過將值轉換為大寫或小寫字母並進行比較來使if語句更好。 然后,您只需要編寫“ N”和“ Y”或“ n”和“ y”的代碼。

您應該使用&&代替|| 在第一個IF和While條件檢查中。

        do {
        System.out.println("Would you like to enter another number? (y/n)");

        restart = console.next().charAt(0);

        if ((restart != 'y') && (restart != 'n') && (restart != 'N') && (restart != 'Y'))
        {
            System.out.println("You entered something other than the letters (y) or (n).");
        }
        else if (restart == 'n' || restart == 'N')
        {
            System.out.println("Goodbye.");
        }
    }
    while ((restart != 'y') && (restart != 'n') && (restart != 'N') && (restart != 'Y'));   

好吧,首先,您不需要為大寫和小寫字母創建選項。 使用.equalsIgnoreCase()。 使用&&代替或,因為您說的是如果他們輸入yes或no,它將重新啟動。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM