Java tutorial- read input values from keyboard |
|||||||||||||||||||||||||||
Read input values from keyboardReading single characterSystem.in.read() method is used to read a single character from user’s input value. It will return numerical value of the input character. Therefore, you need to convert the value to the character using (char) conversion statement otherwise you may not understand what the user input.
Example:
public class Getcha In the sample above, exception must be thrown to pass the errors to the operating system to handle them. If exception is not thrown, your program will not be compiled.
Reading strings There are many ways to read input strings value from user. However, in this tutorial, I introduce one way by using readLine() method. The readLine() method of BufferedReader class can be used to read input strings value from the user. To use this method, you must create BufferedReader object. Example: import java.io.*; // import IO package
public class ReadString BufferedReader reader;//create BufferedReader object reader=new BufferedReader(new InputStreamReader(System.in)); System.out.print(“Enter your name:”); yourname=reader.readLine();
System.out.println(“Your name is ”+yourname);
Type conversions In Java programming language, you can convert from one type of data to another type by specifying that type in brackets (). Example:
public class Conversion In some circumstances, you need to convert a string value to an integer value. Because String is not a simple data type but it is a class type, you cannot convert it as in the above example. Instead, you need to use Interger.parseInt() method of Integer class. Example: import java.io.*; // import IO package
public class ConvertString int val; BufferedReader reader;//create BufferedReader object reader=new BufferedReader(new InputStreamReader(System.in)); System.out.print(“Enter your favorite number:”); valString=reader.readLine(); val=Integer.parseInt(valString); //string value is converted to integer value
System.out.println(“Your favorite number is ”+val);
|
|||||||||||||||||||||||||||
|
|||||||||||||||||||||||||||