简体   繁体   中英

How to ignore case in java when asking for user input in a loop

I'm trying to run this program as a loop when the user inputs a "Y" value in. I want the input to ignore the case, so that the user can enter "y" or "n" also. Would I use the equalsIgnoreCase() method? And if so, would I want to change my char to a boolean? I'm still very new to java about a month in, so any help would be appreciated. I've been playing around with this for awhile now and I can't figure it out without at least one error.The fact that I got it to loop at all is a miracle at this point :)

        char Again = 'Y';
        while(Again == 'Y')
        {
            long product = 1, count = 0;
            System.out.println("This program will generate a table of powers of a number.");
            System.out.println("You just have to tell me what number: \n\n");
            System.out.print("Enter an integer please: ");
            int MyNum = Fred.nextInt();
            while(count<5)
            { product = product * MyNum;
              System.out.print(product + ",");
              count = count + 1;
            }
         System.out.println("\nBye for now.....");
         System.out.print("\n\n\n Try another number (y/n)?");
         String Word = Fred.next();
         Again = Word.charAt(0);
        }

char is primitive data type, it doesn't have member functions. So you need to check both the lower case and upper case if you stick with char:

 while(Again == 'Y' || Again == 'y')

Or, you can declare Again as String : Again = Word.toUpperCase(); then use while("Y".equals(Again))

Or, just, Again = Word; then while("Y".equalsIgnoreCase(Again))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM