Solved

Keyboard input with Scaner class

Posted on 2008-10-18
7
264 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 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
Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
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

Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
iterator/ListIterator approach 17 64
ejb entity bean example issue 2 39
Is there a simpler dropbox system? 10 50
activeMQ Queue Messages Enqueued and Messages Dequeued 1 96
Introduction Java can be integrated with native programs using an interface called JNI(Java Native Interface). Native programs are programs which can directly run on the processor. JNI is simply a naming and calling convention so that the JVM (Java…
In this post we will learn how to connect and configure Android Device (Smartphone etc.) with Android Studio. After that we will run a simple Hello World Program.
Viewers learn about the “while” loop and how to utilize it correctly in Java. Additionally, viewers begin exploring how to include conditional statements within a while loop and avoid an endless loop. Define While Loop: Basic Example: Explanatio…
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.
Suggested Courses

738 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