|
-
Help with the Scanner class
This is my simple Java program:
-----------------------------------------------------------------
import java.util.*;
public class Person{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
sc.useDelimiter("\r");
String name;
int age;
System.out.println("Enter a person's name: ");
name = sc.next();
System.out.println("Enter a person's age: ");
age = sc.nextInt();
System.out.println("Name: " + name + "\nAge: " + age);
}
}
------------------------------------------------------
Now, after I enter an integer for the age I get an InputMismatchException and it says the error is on Line 13 [ age=sc.nextInt(); ]
Can someone explain to me why this happens and how do I correct it?
I've tried changing the data type of age to String and it works just fine.
I also tried removing the sc.useDelimiter("\r") line and it works fine but of course I cannot enter names like "Jane Smith". Does this mean the Scanner cannot recognize the integer I entered or took the "\r" as my data?
By the way, I'm pretty sure the problem is with the Scanner class but if I'm wrong, please correct me.
Similar Threads
-
By Osiris43 in forum .NET
Replies: 1
Last Post: 08-04-2006, 12:15 PM
-
Replies: 5
Last Post: 01-15-2006, 07:10 PM
-
By xdanielx in forum Java
Replies: 5
Last Post: 10-31-2005, 01:50 AM
-
By none_none in forum Java
Replies: 17
Last Post: 04-28-2005, 03:00 PM
-
Replies: 5
Last Post: 10-17-2002, 01:58 PM
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
Forum Rules
|
Top DevX Stories
Easy Web Services with SQL Server 2005 HTTP Endpoints
JavaOne 2005: Java Platform Roadmap Focuses on Ease of Development, Sun Focuses on the "Free" in F.O.S.S.
Wed Yourself to UML with the Power of Associations
Microsoft to Add AJAX Capabilities to ASP.NET
IBM's Cloudscape Versus MySQL
|
Bookmarks