Java Reference
In-Depth Information
some user keyboard input to deliver the solution. Java I/O is quite elaborate
compared to other similar imperative languages like C++ because it has been
designed to fit the object-oriented style that will be explained later on. For
now, consider reading input from the console using the following syntax:
Program 1.13 Reading an integer value
import java . util . ;
class KeyboardIntInput {
public static void main( String [ ] args )
Scanner keyboard= new Scanner(System . in ) ;
int val ;
System . out . print ( "Enter an integer please:" );
val=keyboard . nextInt () ;
System . out . print ( "I read the following value:" );
System . out . println ( val ) ;
}
}
The output of a running session gives:
Enter an integer please:5
I read the following value:5
In the former code, we again used two magic lines, import java.util. ; and
Scanner keyboard= new Scanner(System.in); , which will be fully explained later,
in the second part of this topic.
We can similarly read float and double values using keyboard.nextFloat(); and
keyboard.nextDouble() instructions:
System . out . print ( "Enter a single-precision real please:" );
valf=keyboard . nextFloat () ;
System . out . print ( "I read the following value:" );
System . out . println ( valf ) ;
System . out . print ( "Enter a double precision please:" );
vald=keyboard . nextDouble () ;
System . out . print ( "I read the following value:" );
System . out . println ( vald ) ;
In case the above code snippet yields an error at run time, which is due to
the number formatting conventions 11 , add the instruction keyboard.useLocale(
Locale.US);
11 In the US, real numbers are written using the a decimal dot “.” while in European
countries it is a decimal comma “,.” By default, Java is installed with the country
local settings.
 
 
Search WWH ::




Custom Search