【问题标题】:Java Do-while loop not working?Java Do-while 循环不起作用?
【发布时间】:2014-11-22 03:02:23
【问题描述】:

老实说,当我的 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));
    }


}   

}

如果有人能告诉我问题出在哪里,那就太好了

【问题讨论】:

  • 你确定它完全符合 do while 循环吗?
  • 不,它似乎跳过了回复 = s.nextLine(),因为它甚至没有给我输入任何内容的机会。我不知道它为什么会这样做。

标签: java loops do-while


【解决方案1】:

这行有问题

double tempPrice = s.nextDouble();

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-15
    • 2020-11-26
    • 2022-12-12
    • 1970-01-01
    • 2013-05-06
    • 1970-01-01
    相关资源
    最近更新 更多