Java:输入比较

标签 java string compare

我想知道为什么当我在被问及此方法中是否还有更多数字后键入“y”时,代码可以正常工作并离开循环,但在键入“n”并按回车键后,我需要键入“n' 并再次点击返回,否则进程就会挂起。

为什么?

字符串 'input' 是从 main 方法中的用户输入传递过来的,在本例中是“addition”。

private int add(String input)
    {
        int additionValue = 0;
        boolean keepGoing = true;
        if (input.matches("addition"))
        {

            while (keepGoing == true)
            {
                System.out.println("Next digit = (Type the digit)");
                additionValue = additionValue + scan.nextInt();
                System.out.println("Any more digits? Type y/n");
                if (scan.next().matches("Y|y"))
                {
                    keepGoing = true;
                }
                else if (scan.next().matches("N|n"))
                {
                    keepGoing = false;
                }
                else
                {
                    System.out.println("Great, you broke it.");
                    System.exit(1);
                }
            }
        }
    }

我已经设法让代码通过使用

System.out.println("Any more digits? Type y/n"); 
String yayOrNay = scan.next();
if (yayOrNay.length()==1 && yayOrNay.charAt(0)=='y')
                {
                    keepGoing = true;
                }

但对于我来说,它所做的一切似乎有点太复杂了。

最佳答案

scan.next() 从输入流中提取一个新字符。

因此,当您检查 'n' 并执行 scan.next().matches("Y|y") 时,它实际上会跳过 'n' 进行下一次比较。

解决方案是将 scan.next() 赋值给您可以使用的变量:

        while (keepGoing == true)
        {
            System.out.println("Next digit = (Type the digit)");
            additionValue = additionValue + scan.nextInt();
            System.out.println("Any more digits? Type y/n");
            String next = scan.next();
            if (next.matches("Y|y"))
            {
                keepGoing = true;
            }
            else if (next.matches("N|n"))
            {
                keepGoing = false;
            }
            else
            {
                System.out.println("Great, you broke it.");
                System.exit(1);
            }
        }

关于Java:输入比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19433299/

相关文章:

Python 分割函数。解包错误的值太多

java-8 - Comparator.comparing() 函数如何工作?

javascript - 使用日期精度比较 javascript/jquery 中的两个日期

java - 无法使用 Spring : javax. mail.FolderClosedException 读取电子邮件正文

java - 如何在 Android 应用程序中保存天文钟耗时

C++: vector<set<string>> 函数初始化

C++:为什么空格在读取时总是终止字符串?

java - java的compareTo()函数中字符的层次结构

java - body 在撞墙时失去了一个速度分量

java - Android图像淡入淡出动画