简体   繁体   中英

Java Do-while loop not working?

I honestly have no idea while my do-while loop is not working. Every time I run the program it just skips over it and moves on without even asking for the reply.

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));
    }


}   

}

If anyone could tell me what the problem is that would be great

Problem is with this line

double tempPrice = s.nextDouble();

It only reads a double value and not the newline after that, and your newline will be read by the nextLine() after the nextDouble() . In order to prevent that add a s.nextLine() after s.nextDouble() to read the newline

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM