problem with java

Thread Starter

silvrstring

Joined Mar 27, 2008
159
Hey AAC.

I am having a problem with the simplest java program. As an exercise, I just have to use an array of objects to collect and return simple data. I did it with C++, no problem. I have it working in Java, but for some reason, it skips the name entry after the first round.

I have attached the Class file (StudentType) I am using for objects, and I have attached the main file (studentMain). They are both very simple and short. I also attached a screenshot of the Win32 console, so you can see what I mean.

Thanks, if you can explain why this is happening.
Silvrstring
 

Attachments

Mark44

Joined Nov 26, 2007
628
Try changing the type of Idnum to String (and IDNumber in Main) and see if that makes a difference. There's no reason that Idnum should be an integer, since you're not going to be doing any arithmetic to it.

I suspect that the problem you're having results from the difference between how nextInt and nextLine operate with integers and strings.

You'll also want to change your second for loop in studentMain as follows:
Rich (BB code):
System.out.println("Enter ID#:");
IDnumber = cin.nextLine();
student.setIDnum(IDnumber);
 

Mark44

Joined Nov 26, 2007
628
Just guessing, but it might be that this is what is happening. Here's the first iteration of your loop.
Enter student name: Rob<Enter>
Enter major: CET<Enter>
Enter ID#: 765<Enter>

When cin.nextInt() is called in the last line above, it builds an integer from the characters ('0', '1', ..., '9') entered. As long as you enter a string of numeric characters, it keeps building the integer. It quits, I believe, on receiving the first nonnumeric character, such as the Enter key, which translates to <CR> <LF> on Windows and just <CR> on Unix or Linux.

Because whatever character or characters weren't used for the integer, they're still in the input buffer, and the next time you call cin.nextLine(), then it/they are consumed.

The best choice, IMO, is to make the ID "number" a string, as I suggested before. An alternate approach that you might want to try is to flush the input buffer after your program reads in the major. I haven't done anything in Java for about 14 years, so I'm pretty rusty, but check to see if the cin class has a flush() method.

Assuming there is such a method, the code would look like this.

Rich (BB code):
System.out.println("Enter major: ");
major = cin.nextLine();
student.setMajor(major);
			
System.out.println("Enter ID#:");
IDnumber = cin.nextInt();
cin.flush();  // <--- flush the input buffer
student.setIDnum(IDnumber);
 
Top