虽然循环不会终止,即使条件满足 - Java

时间:2013-04-16 13:33:27

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

我不确定出了什么问题,我的教授也很难过。 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 个答案:

答案 0 :(得分:4)

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

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

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