如何在循环中请求用户输入时忽略java中的大小写

时间:2022-12-03 10:23:42

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 :)

当用户输入“Y”值时,我试图将此程序作为循环运行。我希望输入忽略大小写,以便用户也可以输入“y”或“n”。我会使用equalsIgnoreCase()方法吗?如果是这样,我想将我的char更改为布尔值吗?大约一个月我对java仍然很新,所以任何帮助都会受到赞赏。我已经玩了一段时间了,而且至少有一个错误,我无法解决这个问题。事实上,我完全循环它是一个奇迹,在这一点上:)

        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);
        }

1 个解决方案

#1


3  

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:

char是原始数据类型,它没有成员函数。因此,如果你坚持使用char,你需要检查小写和大写:

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

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

或者,您可以将Again声明为String:Again = Word.toUpperCase();然后使用while(“Y”.equals(再次))

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

或者,只是,再次= Word;然后while(“Y”.equalsIgnoreCase(再次))

#1


3  

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:

char是原始数据类型,它没有成员函数。因此,如果你坚持使用char,你需要检查小写和大写:

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

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

或者,您可以将Again声明为String:Again = Word.toUpperCase();然后使用while(“Y”.equals(再次))

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

或者,只是,再次= Word;然后while(“Y”.equalsIgnoreCase(再次))