Java Do-while循环不起作用?

时间:2014-11-22 03:02:24

标签: java loops do-while

老实说我不知道​​我的do-while循环不起作用。每次我运行该程序时,它只是跳过它并继续前进,甚至没有要求回复。

import java.util.*;

public class CourseApp {
    public static void main(String[] args) {

    Scanner s = new Scanner(System.in);
    ArrayList <Course> courseList = new ArrayList<Course>();

    String reply;
    //boolean boolVal = true;

    do {
        System.out.print("Enter new course number: ");
        String tempCourseNum = s.nextLine();

        System.out.print("Enter course name: ");
        String tempCourseName = s.nextLine();       

        System.out.print("Enter instructor's last name: ");
        String tempLastName = s.nextLine();

        System.out.print("Enter instructor's first name: ");
        String tempFirstName = s.nextLine();

        System.out.print("Enter instructor's username: ");
        String tempUsername = s.nextLine();

        //new Instructor(tempLastName, tempFirstName, tempUsername);
        Instructor tempInstruc = new Instructor(tempLastName, tempFirstName, tempUsername);

        System.out.print("Enter textbook title: ");
        String tempTitle = s.nextLine();

        System.out.print("Enter textbook author: ");
        String tempAuthor = s.nextLine();

        System.out.print("Enter textbook price (no $ sign): ");
        double tempPrice = s.nextDouble();

        //new TextBook(tempTitle, tempAuthor, tempPrice);
        TextBook tempText = new TextBook(tempTitle, tempAuthor, tempPrice); 

        courseList.add(new Course(tempCourseNum, tempCourseName, tempInstruc, tempText ));

        System.out.print("\nEnter another course? (y/n): ");
        reply = s.nextLine();

    } while (reply.equalsIgnoreCase("Y"));

    for (int i =0; i < courseList.size(); i++) {
        System.out.println("\n\tCourse #" + (i+1)+":");
        System.out.println(courseList.get(i));
    }


}   

}

如果有人能告诉我这个问题会有什么好处

1 个答案:

答案 0 :(得分:1)

问题在于这一行

double tempPrice = s.nextDouble();

它只读取一个双精度值,而不是之后的换行符,nextLine()之后的nextDouble()将读取换行符。为了防止在s.nextLine()之后添加s.nextDouble()来阅读换行符

double tempPrice = s.nextDouble();
s.nextLine();