【问题标题】:While loop not terminating even when condition is met-Java即使满足条件,while循环也不会终止-Java
【发布时间】:2013-04-08 22:41:25
【问题描述】:

我不确定出了什么问题,我的教授也很困惑。只有当条件立即满足时,while 循环条件才会终止。一旦循环运行,满足条件不再停止它,它只会继续运行。看起来好像不再检查状况了?下面是我的代码。感谢您的帮助。

    import java.io.*;
    import java.util.*;


public class createPhoneList {

    public static void main(String[] args) {

        DataOutputStream ostream;//creates output stream
        Scanner input = new Scanner(System.in);//creates scanner in object
        final String DONE = "DONE";//will be used to end data entry loop
        String firstName;
        String lastName;
        long phoneNumber;

        try{
            ostream = new DataOutputStream(new   FileOutputStream("javaContactsUnit4Assignment.txt"));
            System.out.print("Enter First Name or type 'DONE' to quit: ");
            firstName = input.nextLine();
            while(!firstName.equalsIgnoreCase(DONE)){
                /*
                 * Error occuring at runtime where while loop terminates only if
                 * "done" is typed first, but once the loop is running "done" no longer
                 * stops it. Not sure what is wrong...
                 */
                input.nextLine();
                System.out.print("Please enter Last Name: ");
                lastName = input.nextLine();
                System.out.print("Please enter the Phone Number(with NO DASHES, as they will cause a fatal error): ");
                phoneNumber = input.nextLong();
                ostream.writeUTF(firstName);
                ostream.writeUTF(lastName);
                ostream.writeLong(phoneNumber);

                System.out.print("Enter First Name or type 'DONE' to quit: ");
                firstName = input.nextLine();
                }

        }
        catch(IOException e){
            System.err.println("Error opening file.");
        }
        catch(InputMismatchException e){
            System.err.println("Invalid data was entered. Please try again.");
        }
        catch(Exception e){
            System.err.println("You encountered a fatal error. Please try again.");
        }

    }
}

【问题讨论】:

    标签: java while-loop runtime-error infinite-loop


    【解决方案1】:

    您应该在phoneNumber = input.nextLong(); 之后添加另一个input.nextLine();

    这是因为input.nextLong() 命令只读取长值(并跳过\n,这是您紧随其后按下的回车键)。

    因此,当您继续使用input.nextLine() 阅读时,您会收到\n 而不是"done",这就是您的循环永远不会终止的原因。因此,添加另一个input.nextLine()“吞下”\n,而下一个将读取实际的字符串。

    【讨论】:

    • 那么为什么当我将所有“Long”变量类型都更改为“Int”时它仍然一团糟?如果如您所说,更改它也应该修复它,但它没有。不过,这是一个非常好的答案。
    • nextInt 也是如此,只需在阅读 int/long/double 后添加另一个 nextLine.. 看我的解释。
    猜你喜欢
    • 2016-03-14
    • 2020-04-15
    • 1970-01-01
    • 1970-01-01
    • 2021-08-07
    • 1970-01-01
    • 2012-10-01
    • 2022-10-13
    • 2019-01-29
    相关资源
    最近更新 更多