Quantcast
Channel: Programming Forums
Viewing all articles
Browse latest Browse all 51036

Sentinel controlled while-loop problem

$
0
0
Hi everybody, I'm new to this site, so please bear with me and give me suggestions as to how I can improve my question-asking. If you need more information, please tell me.

I'm writing a test driver class to test my Student, and Course, and Course subclasses).

My goal is to scan in a text file for input and then create a student, and then Courses for that student. Sample input would look like this:

Jane Doe
CS1083 4 A+ 1
HIST1305 3 D 4
CS1073 4 A- 1
end



The problem is trying to quit the while loop. My code so far looks like this:

        ...

        String end = "end";

        Scanner scan = new Scanner(System.in);
        
        first = scan.next();
        last = scan.next();
        
        Student stu = new Student(first, last);
        
        do
        {
            title = scan.next();
            credit = scan.nextInt();
            grade = scan.next();
            category = scan.nextInt();
            
            if (category == 1)
            {
                Course cat1 = new Category1(title, grade, credit);
                stu.addCourse(cat1);
            }
            
            else if (category == 2)
            {
                Course cat2 = new Category2(title, grade, credit);
                stu.addCourse(cat2);
            }
            
            else if (category == 3)
            {
                Course cat3 = new Category3(title, grade, credit);
                stu.addCourse(cat3);
            }
            
            else if (category == 4)
            {
                Course cat4 = new Category4(title, grade, credit);
                stu.addCourse(cat4);
            }
            
            else
            {
                System.out.println("Invalid category");
            }
            
        } while (!(scan.next()).equals(end));

        System.out.println(stu.toString());

...



I can enter a first name, last name, and 1 course fine:

Jane Doe
CS1083 4 A+ 1
end



But when I try to keep going (enter a new course), it gives me an InputMismatchException.

I'm pretty sure the problem is that, where I have

 
        } while (!(scan.next()).equals(end));



, it is scanning for another String, instead of going back up and scanning for another title. I just don't know quite how to fix it.

Any help and suggestions would be greatly appreciated. As you can see, this is a pretty simple problem, but I'm not a very experienced programmer :)/>.

Viewing all articles
Browse latest Browse all 51036

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>