?
Solved

Keyboard input with Scaner class

Posted on 2008-10-18
7
Medium Priority
?
268 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 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 2000 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
Get 15 Days FREE Full-Featured Trial

Benefit from a mission critical IT monitoring with Monitis Premium or get it FREE for your entry level monitoring needs.
-Over 200,000 users
-More than 300,000 websites monitored
-Used in 197 countries
-Recommended by 98% of users

 
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

New benefit for Premium Members - Upgrade now!

Ready to get started with anonymous questions today? It's easy! Learn more.

Question has a verified solution.

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

Introduction This article is the first of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article explains our test automation goals. Then rationale is given for the tools we use to a…
In this post we will learn how to make Android Gesture Tutorial and give different functionality whenever a user Touch or Scroll android screen.
Viewers will learn about basic arrays, how to declare them, and how to use them. Introduction and definition: Declare an array and cover the syntax of declaring them: Initialize every index in the created array: Example/Features of a basic arr…
This theoretical tutorial explains exceptions, reasons for exceptions, different categories of exception and exception hierarchy.
Suggested Courses
Course of the Month12 days, 19 hours left to enroll

777 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