当条件满足时,While循环未终止-Java。

3

我不确定问题出在哪里,我的教授也被难住了。只有当条件立即满足时,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.");
        }

    }
}
1个回答

4
您需要在phoneNumber = input.nextLong();后再添加一个input.nextLine();
这是因为input.nextLong()命令只读取长整型值(并跳过您按下的回车键\n)。
因此,当您继续使用input.nextLine()进行读取时,您将收到\n而不是"done",这就是为什么您的循环永远不会终止的原因。 因此,添加另一个input.nextLine()将“吞掉”\n,而下一个将读取实际的字符串。

那么,如果我将所有的“Long”变量类型更改为“Int”,为什么它仍然出现问题?如果按照您所说的更改应该已经解决了问题,但实际上并没有。不过,您的回答非常好。 - user2286647
对于 nextInt,同样的情况也会发生,只需在读取 int/long/double 后再添加另一个 nextLine 即可。请参考我的解释。 - Maroun

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接