Solved

Keyboard input with Scaner class

Posted on 2008-10-18
7
260 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
Free Tool: Subnet Calculator

The subnet calculator helps you design networks by taking an IP address and network mask and returning information such as network, broadcast address, and host range.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

 
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

Free Tool: Site Down Detector

Helpful to verify reports of your own downtime, or to double check a downed website you are trying to access.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
servlet  URL Rewriting 1 42
windows explorer path to command prompt 5 54
ejb on wildfly 5 30
Running JavaFX on the Raspberry Pi 27 36
An old method to applying the Singleton pattern in your Java code is to check if a static instance, defined in the same class that needs to be instantiated once and only once, is null and then create a new instance; otherwise, the pre-existing insta…
Java functions are among the best things for programmers to work with as Java sites can be very easy to read and prepare. Java especially simplifies many processes in the coding industry as it helps integrate many forms of technology and different d…
This tutorial covers a step-by-step guide to install VisualVM launcher in eclipse.
This video teaches viewers about errors in exception handling.

792 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