Java Help Please

  • Thread starter Thread starter Garee
  • Start date Start date

Garee

Garee

I am working on one of my university Java course assessments and I keep experiencing this error.

Code:
Exception in thread "main" java.util.InputMismatchException
	at java.util.Scanner.throwFor(Unknown Source)
	at java.util.Scanner.next(Unknown Source)
	at java.util.Scanner.next(Unknown Source)
	at Person.<init>(Person.java:49)
	at ProcessMembers.main(ProcessMembers.java:22)

This occurs in my Person class constructor.

Code:
	public Person( Scanner inputScanner )
	{
		this.lastName = inputScanner.next();
		this.firstName = inputScanner.next(",");
		this.male = Gender( inputScanner.next(",") );
		this.dateOfBirth = new Date( inputScanner.nextInt(), inputScanner.nextInt(), inputScanner.nextInt() ); 
	}

The Scanner in this case is reading from a text file containing details of some people in the format:

Code:
Adams Bill, M, 16 03 63

The problem seems to be the delimiter "," as the code compiles correctly when I only use .next()


Any help is much appreciated, thanks.
 
Someone correct me if I'm wrong, but wouldn't you need to change delimiter by using inputScanner.useDelimiter(", ");? Obviously, you'd then have to change it back once you were done using that specific delimiter.
 
Someone correct me if I'm wrong, but wouldn't you need to change delimiter by using inputScanner.useDelimiter(", ");? Obviously, you'd then have to change it back once you were done using that specific delimiter.

I think you may be right. I mis-read the API and thought it was similiar to the way .split(",") is used.
 
I think you may be right. I mis-read the API and thought it was similiar to the way .split(",") is used.

Yeah. I mean, I don't remember anything anywhere saying that there was another way to specify delimiter when using the API, but I could be wrong about it. Let us know how it turns out. :)
 
http://download.oracle.com/javase/1.5.0/docs/api/java/util/Scanner.html

Not meaning that in an arsey way, but Java's Javadocs are the best place to learn. A habit of mine is to take the 30 secs to read the Javadoc segment for any method/class I'm using instead of just relying on auto-complete to search through the methods of a class and effectively brute force them :p I've learnt a great deal of stuff about Java/JVM just from doing that.

'Pro-tip': if you're using Netbeans (and probably Eclipse?), just right-click on the method you're using/trying to use and click navigate to source - that way you get the benefit of the Javadoc and also get to see how Sun have actually gone about implementing it - again, great for learning new stuff. Funny to see some 'familiar faces' like Josh Bloch in amongst the code too.

Back to the point: as has been said (and you were correctly guessing at anyway), you're using hasNext() in the wrong way.
 
Back
Top Bottom