程序要求两次相同的响应?

时间:2017-09-20 01:21:35

标签: java arraylist records

我的学生记录计划要求用户在do while循环中输入学生的名字一次。用户可以通过输入yes和相同的问题再次输入相同的数据"输入学生的名字:"在另一个上面出现两次。

我在while循环中插入了断点,一旦用户选择"是"在do的结尾处,它在第一个while循环中上升到第一行,然后是第二行,第三行,然后再次返回第一行,然后是第二行,第三行,然后进入下一个while循环询问为了学生的姓氏。

为什么我的程序在do while循环的第二次执行期间将第一个问题两次首先吐出一个?

package assignment_3;

import java.util.Scanner;

/**
 * @author Diego
 */
public class Demo {

    public static void main (String args[]) {

    //Instantiating new recordsObject
        StudentRecords recordsObject = new StudentRecords();
        String firstName = "";
        String lastName = "";
        String idNumber = "";
        String major = "";         

        Scanner keyboard = new Scanner(System.in);   

        //Asking the user to enter the students' info

        do {

            while ( firstName.isEmpty() ) {
                System.out.println("Enter student's first name: ");
                firstName = keyboard.nextLine();   
            }

           while ( lastName.isEmpty() ) {
                System.out.println("Enter student's last name: ");   
                lastName = keyboard.nextLine();
            }

            while ( idNumber.length() != 9 ) {
                System.out.println("Enter student's nine-digit ID#: ");
                idNumber = keyboard.nextLine();
            }

            while ( major.isEmpty() ) {
                System.out.println("Enter student's major: ");
                major = keyboard.nextLine();
            }

            //Concatinating first name and last name into name
            String name = firstName + " " + lastName;

            //Adding the new entry to the StudentArrayList
            StudentEntry entry = new StudentEntry (name ,idNumber, major);
            recordsObject.addStudentEntry (entry);

            //Resetting variables
            firstName = "";
            lastName = "";
            idNumber = "";
            major = "";

           /*If the user enters "yes" then they can submit more.
            If they enter "no", then all submitted info will be shown */
            System.out.println("Type yes to add another entry");
        } while (keyboard.next().equalsIgnoreCase("YES"));
        keyboard.close();

        //Printing out those entries

        System.out.println("Student Records");
        System.out.println("---------------");
        for (int index = 0 ; index < recordsObject.StudentArrayList.size() ; index++) {
            System.out.println(recordsObject.StudentArrayList.get(index));
            System.out.println("");
        }
    }
}

1 个答案:

答案 0 :(得分:0)

问题是由主while循环中使用keyboard.next()引起的。接下来不会读取换行符。因此,当用户键入&#34; yes&#34;时,读取下一个firstName的代码将自动读取剩余的换行符,仍将firstName保留为空。并且,由于firstName保持为空,它将再次提示。

变化:

} while(keyboard.next()。equalsIgnoreCase(&#34; YES&#34;));

致:

} while(keyboard.nextLine()。equalsIgnoreCase(&#34; YES&#34;));

相关问题