Solved

Keyboard input with Scaner class

Posted on 2008-10-18
7
252 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
How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

 
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

Find Ransomware Secrets With All-Source Analysis

Ransomware has become a major concern for organizations; its prevalence has grown due to past successes achieved by threat actors. While each ransomware variant is different, we’ve seen some common tactics and trends used among the authors of the malware.

Join & Write a Comment

Suggested Solutions

Title # Comments Views Activity
sumDigits  challenge 7 62
create a gui in perl 3 46
GUI builder for Eclipse? 8 13
HSSFWorkbook cannot be resolved error 10 23
For customizing the look of your lightweight component and making it look opaque like it was made of plastic.  This tip assumes your component to be of rectangular shape and completely opaque.   (CODE)
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…
Viewers will learn about the different types of variables in Java and how to declare them. Decide the type of variable desired: Put the keyword corresponding to the type of variable in front of the variable name: Use the equal sign to assign a v…
This theoretical tutorial explains exceptions, reasons for exceptions, different categories of exception and exception hierarchy.

762 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

Need Help in Real-Time?

Connect with top rated Experts

18 Experts available now in Live!

Get 1:1 Help Now