Solved

Keyboard input with Scaner class

Posted on 2008-10-18
7
257 Views
Last Modified: 2013-12-29
Why in the code below, as fname is taken the "enter" string? What is the problem with
code = in.nextInt(); ?
import java.util.*;
 
class testInput{
	public static void main(String[] args){
	Scanner in = new Scanner(System.in);
	
	int code;
	String fname,lname;
	
	System.out.print("code: ");
	code = in.nextInt();
	System.out.print("first name: ");
	fname = in.nextLine();
	System.out.print("last name: ");
	lname = in.nextLine();
	System.out.printf("code: %d fname: %s lname: %s \n",code,fname,lname);
 
	}
	
	
}

Open in new window

0
Comment
Question by:xiromdim
  • 6
7 Comments
 
LVL 24

Expert Comment

by:sciuriware
ID: 22751174
As 'fname' stands for a file name it must be a String.
An int can only be an integral number.

;JOOP!
0
 
LVL 24

Expert Comment

by:sciuriware
ID: 22751177
This is conform the output line:

        System.out.printf("code: %d fname: %s lname: %s \n",code,fname,lname);

where %s means the output of a String of text.

;JOOP!
0
 
LVL 24

Accepted Solution

by:
sciuriware earned 500 total points
ID: 22751190
By the way:

        code = in.nextInt();

takes only the next number, thereafter

        fname = in.nextLine();

will take the remainder of the line.
In this interactive program, that is not what you want.
Here is an alternative:

import java.util.*;
 
class testInput
{
        public static void main(String[] args)
        {
                Scanner in = new Scanner(System.in);

                String s;              // Little helper.        
                int code;
                String fname,lname;
       
                System.out.print("code: ");
                s = in.nextLine();                      // Entire input.
                try
                {
                    code = Integer.parseInt(s);     // This can fail if the input is bad
                 }
                catch(Exception e)
                {
                    code = -1;               // Or handle the error
                }
     
                System.out.print("first name: ");
                fname = in.nextLine();
                System.out.print("last name: ");
                lname = in.nextLine();
                System.out.printf("code: %d fname: %s lname: %s \n", code, fname,
                                 lname);
 
        }
}

;JOOP!
0
Courses: Start Training Online With Pros, Today

Brush up on the basics or master the advanced techniques required to earn essential industry certifications, with Courses. Enroll in a course and start learning today. Training topics range from Android App Dev to the Xen Virtualization Platform.

 
LVL 24

Expert Comment

by:sciuriware
ID: 22751195
P.S.

                catch(Exception e)

can be narrowed to:

                catch(NumberFormatException e)

to distinguish from other possible errors.

;JOOP!
0
 

Author Comment

by:xiromdim
ID: 22752621
dear sciuriware,
how can we write "defentive" code for data input?
for example in the above code read again and again code until the user enters an integer
(we dont accept floats, nor chars, nor strings...)
thanks
0
 
LVL 24

Expert Comment

by:sciuriware
ID: 22753187
'defensive input'?

best to isolate such inputs per item in a method, like:

import java.nio.channels.CancelledKeyException;


int inputCode() throws CancelledKeyException // on empty input
{
// Now it is this method's responsibility to return a code or throw an exception if
// the user gives up.

    int code = -1;

    while(code == -1)
    {
//  prompt for input
// read input
// nothing? EXCEPTION!
// parse
// format exception?
// then: complain, continue
// return code
    }
}

By isolating code in sub-projects you can easily give tasks to programmers
but also re-use such a method in another project.

;JOOP!
0
 
LVL 24

Expert Comment

by:sciuriware
ID: 22753190
I wonder where your home is ...............................................
0

Featured Post

Courses: Start Training Online With Pros, Today

Brush up on the basics or master the advanced techniques required to earn essential industry certifications, with Courses. Enroll in a course and start learning today. Training topics range from Android App Dev to the Xen Virtualization Platform.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
allswap challenge 6 96
web services creation SOAP vs REST 5 39
eclipse buid path vs tomcat lib path 10 22
JavaFX TableView not displaying correctly 3 16
Java contains several comparison operators (e.g., <, <=, >, >=, ==, !=) that allow you to compare primitive values. However, these operators cannot be used to compare the contents of objects. Interface Comparable is used to allow objects of a cl…
Are you developing a Java application and want to create Excel Spreadsheets? You have come to the right place, this article will describe how you can create Excel Spreadsheets from a Java Application. For the purposes of this article, I will be u…
Viewers will learn about if statements in Java and their use The if statement: The condition required to create an if statement: Variations of if statements: An example using if statements:
This tutorial will introduce the viewer to VisualVM for the Java platform application. This video explains an example program and covers the Overview, Monitor, and Heap Dump tabs.

776 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question