Welcome to Dream.In.Code
Become a Java Expert!

Join 149,574 Java Programmers for FREE! Get instant access to thousands of Java experts, tutorials, code snippets, and more! There are 1,689 people online right now. Registration is fast and FREE... Join Now!




Little problem with while loop

 
Reply to this topicStart new topic

Little problem with while loop, scanner issue?

sgmikewoody
17 Oct, 2007 - 05:14 PM
Post #1

New D.I.C Head
*

Joined: 30 Sep, 2007
Posts: 15


My Contributions

Each time it reads two names, it automatically prints out another "enter student name" again. I've tried searching the net, this website, and asked my teacher. Hah, what good that did. Any help is appreciated.

I got it to work by creating vars for first and last names, but that's not exactly the parameter of the assignment and what if the person had 3 names? I'm not the type of person to half ass something. Thanks in advance,

Mike

CODE
import java.io.*;
import java.util.*;

public class Roster1
{
    public static void main(String [] args) throws
                                                            FileNotFoundException
    {
            
        PrintWriter outFile = new
                            PrintWriter("c:\\Java\\student1.dat");
        
        Scanner console = new Scanner(System.in);
        
        int class_limit;
        int counter = 0;
        String student_name;
        
        System.out.println("This program asks the user to enter the\n"
                                + "number and the names of the students in "
                                + "a course.\n");
                                
        
        System.out.print("How many student are registered for this class? ");
        class_limit = console.nextInt();
                                
        while (class_limit != counter)
            {
                System.out.print("Enter the student's name: ");
                student_name = console.next();
                ++counter;
                    outFile.println(student_name);
                
            }
        
        System.out.println("\nThe class is full.");            
        outFile.close();                    
                    
                    
        }
    }

User is offlineProfile CardPM
+Quote Post

Martyr2
RE: Little Problem With While Loop
17 Oct, 2007 - 06:43 PM
Post #2

Programming Theoretician
Group Icon

Joined: 18 Apr, 2007
Posts: 5,655



Thanked: 313 times
Expert In: C/C++, Java, VB, VB.NET, C#, PHP, Web Development, HTML & CSS, Javascript

My Contributions
You are suffering from a really simple problem, but a common one for those new to the language. It is how you are reading in your data from the user. First you use console.nextInt() which has one side effect when collecting user input, it leaves carriage returns in the buffer. It just reads in the integer. Right now it isn't an issue, but when we do the next change you will see why it will be...

The second part is how you read in the student's name. Using just next() of the scanner object will read tokens... in this case tokens separated by a space. So I was to enter "Martyr Two" the first call to next() would read in "Martyr" and the next call would read in "Two". To fix this, use another method like nextLine() which will read up to the first line break, thus read in the entire students name.

Now why this little nextLine() change will be an issue with your first one is because when the user enters a value like "2" for the number of students and hits enter it will read in the 2 and leave the carriage return for your nextLine to read, which will make it appear to skip over your first student and repeat the prompt for a student's name.

So how do we fix it? Glad you asked. The trick is to go ahead and make the change for the student's_name to use nextLine() and back for collecting the number, use nextLine as well, but parse it into an integer like so...

CODE

// Collect what they typed, then change it to an integer.
class_limit = Integer.parseInt(console.nextLine());


The beauty of this is that it will read up the carriage return as well and leave nothing behind, then convert what they typed to a number for use in the rest of your program. Then your other nextLine() calls will work as expected and collect their full name.

One warning though, when collecting the number in the class, make sure you check if the user entered a number. If they enter letters or characters, it will throw an error in your parseInt (which you could trap if you like).

But since it is a simple program, you can choose to let it go and assume the user always enters a number.

Hope this helps your understanding. Let your instructor know what you have learned here. wink2.gif

"At DIC we be coding ninjas!" decap.gif
User is offlineProfile CardPM
+Quote Post

sgmikewoody
RE: Little Problem With While Loop
17 Oct, 2007 - 06:51 PM
Post #3

New D.I.C Head
*

Joined: 30 Sep, 2007
Posts: 15


My Contributions
QUOTE(Martyr2 @ 17 Oct, 2007 - 07:43 PM) *

You are suffering from a really simple problem, but a common one for those new to the language. It is how you are reading in your data from the user. First you use console.nextInt() which has one side effect when collecting user input, it leaves carriage returns in the buffer. It just reads in the integer. Right now it isn't an issue, but when we do the next change you will see why it will be...

The second part is how you read in the student's name. Using just next() of the scanner object will read tokens... in this case tokens separated by a space. So I was to enter "Martyr Two" the first call to next() would read in "Martyr" and the next call would read in "Two". To fix this, use another method like nextLine() which will read up to the first line break, thus read in the entire students name.

Now why this little nextLine() change will be an issue with your first one is because when the user enters a value like "2" for the number of students and hits enter it will read in the 2 and leave the carriage return for your nextLine to read, which will make it appear to skip over your first student and repeat the prompt for a student's name.

So how do we fix it? Glad you asked. The trick is to go ahead and make the change for the student's_name to use nextLine() and back for collecting the number, use nextLine as well, but parse it into an integer like so...

CODE

// Collect what they typed, then change it to an integer.
class_limit = Integer.parseInt(console.nextLine());


The beauty of this is that it will read up the carriage return as well and leave nothing behind, then convert what they typed to a number for use in the rest of your program. Then your other nextLine() calls will work as expected and collect their full name.

One warning though, when collecting the number in the class, make sure you check if the user entered a number. If they enter letters or characters, it will throw an error in your parseInt (which you could trap if you like).

But since it is a simple program, you can choose to let it go and assume the user always enters a number.

Hope this helps your understanding. Let your instructor know what you have learned here. wink2.gif

"At DIC we be coding ninjas!" decap.gif



I could marry you, seriously thank you. I've been working on this problem for about a week now which has seriously put me behind. Thank you so much for your help and patience. I definitely understand now.

No one told me this class would be so hard. The saddest part is that it's not the material that's hard, it's figuring it all out on your own that frustrates me.
User is offlineProfile CardPM
+Quote Post

Martyr2
RE: Little Problem With While Loop
17 Oct, 2007 - 06:56 PM
Post #4

Programming Theoretician
Group Icon

Joined: 18 Apr, 2007
Posts: 5,655



Thanked: 313 times
Expert In: C/C++, Java, VB, VB.NET, C#, PHP, Web Development, HTML & CSS, Javascript

My Contributions
You are quite welcome. That is what we do here is help. And in the words of a great man here on DIC.... "Be sure to tell your friends about us!" hahaha (inside joke) smile.gif


User is offlineProfile CardPM
+Quote Post

skyhawk133
RE: Little Problem With While Loop
17 Oct, 2007 - 07:01 PM
Post #5

Head DIC Head
Group Icon

Joined: 17 Mar, 2001
Posts: 15,262



Thanked: 61 times
Dream Kudos: 1650
Expert In: Web Development

My Contributions
wink2.gif
User is offlineProfile CardPM
+Quote Post

Fast ReplyReply to this topicStart new topic
Time is now: 1/7/09 10:28PM

Be Social

Dream.In.Code RSS Feed Dream.In.Code LinkedIn Group Follow Us On Twitter

Live Java Help!

Java Tutorials

Reference Sheets

Java Snippets

DIC Chatroom

Bye Bye Ads

Monthly Drawing

Thumb Drive

Top Contributors

Top 10 Kudos This Month