In
this post, I will try how to make program that java response from
console, what in my concern is no matter you put any kind type data
in console such char, string, and Number, we always use the same
class InputStreamReader
and BufferedReader,
the differences is how we manipulate that data capture from console.
I will start from from simple for char type.
import
java.io.BufferedReader;
import
java.io.IOException;
import
java.io.InputStreamReader;
public
class
CharacterInputDemo {
public
static
void
main(String[] args) throws
IOException {
//
TODO
Auto-generated method stub
System.out.println("Please
Input Random Character : ");
char
character;
InputStreamReader
input = new
InputStreamReader(System.in);
BufferedReader
buffer = new
BufferedReader(input);
character
= (char)
buffer.read();
System.out.println("Character \'"+character+"\'");
}
}
as we see above our input was casting to char, because every time retrieve value from BufferedReader class the data type is integer, because we want in char type then we cast integer to char. Now I will show if we want capture string type from console ok, take look code bellow:
import
java.io.BufferedReader;
import
java.io.IOException;
import
java.io.InputStreamReader;
public
class StringInputDemo {
public
static
void
main(String[] args) throws
IOException {
System.out.println("what
is your name ? ");
String
name;
InputStreamReader
input = new
InputStreamReader(System.in);
BufferedReader
buffer = new
BufferedReader(input);
name
= buffer.readLine();
System.out.println("Hello,
"+name+"
nice too meet you !");
}
}
as we see above we don’t have to casting from the input that we have put because BufferedReader class have method “readLine()” to capture from console and when we retrieve automatic in string form. Now I will show how to what if put number type like integer, check out the code bellow:
import
java.io.BufferedReader;
import
java.io.IOException;
import
java.io.InputStreamReader;
public
class
NumberInputDemo {
public
static
void
main(String[] args) throws
IOException {
String
temp;
int
a = 0;
System.out.println("Pick
a number please ? ");
InputStreamReader
input = new
InputStreamReader(System.in);
BufferedReader
buffer = new
BufferedReader(input);
temp
= buffer.readLine();
try
{
a
= Integer.parseInt(temp);
System.out.println("the
power 2 of your value "+a*a);
}catch(NumberFormatException numberFormatException) {
System.err.println("Data
that you has put "+temp+"notnumber");
}
}
}
As
we see above we capture value from console was same as we for string
value, the difference is we convert to the format as we want and prevent
if we put not in number form.
No comments:
Post a Comment