Lets first see what we mean by standard stream in java. Click here.
- Using scanner
To read console input, you first construct a Scanner that is attached to the "standard input stream" System.in.
Now you use the various methods of the Scanner class to read input. For example, the nextLine method reads a line of input.Scanner in = new Scanner(System.in);
Here, we use the nextLine method because the input might contain spaces. To read a single word (delimited by whitespace), callSystem.out.print("What is your name? ");
String name = in.nextLine();To read an integer, use the nextInt method.String firstName = in.next();
Similarly, the nextdouble method reads the next floating-point number.System.out.print("How old are you? ");
int age = in.nextInt();
Finally, add the lineimport java.util.*;
- Using JOptionPane
String input = JOptionPane.showInputDialog(promptString)
eg.
String name = JOptionPane.showInputDialog("What is your name?");
Entering Integers
String name = JOptionPane.showInputDialog("What is your age?");
int age = Integer.parseInt(input);
Importimport javax.swing.*;
Finally, whenever your program calls JOptionPane.showInputDialog, you need to end it with a call to System.exit(0). The reason is a bit technical. Showing a dialog box starts a new thread of control. When themain method exits, the new thread does not automatically terminate. Toend all threads, you call the System.exit method. - Using BufferedReader Its most commonly used constructor is shown here:
BufferedReader(Reader inputReader)
Here, inputReader is the stream that is linked to the instance of BufferedReader that is being created. Reader is an abstract class. One of its concrete subclasses is InputStreamReader, which converts bytes to characters. To obtain an InputStreamReader object that is linked to System.in, use the following constructor:
InputStreamReader(InputStream inputStream)
So basic step is :InputStreamReader inp = new InputStreamReader(System.in)
BufferedReader br = new BufferedReader(inp);
Now to read character :char c = br.read();
To read String:String str = br.readLine();
- Reading Characters
int read( ) throws IOException
Each time that read( ) is called, it reads a character from the input stream and returns it
as an integer value. It returns –1 when the end of the stream is encountered. As you can
see, it can throw an IOException.char c;
BufferedReader br = new
BufferedReader(new InputStreamReader(System.in));
c = (char) br.read();
System.out.println(c) - Reading strings
String readLine( ) throws IOExceptionBufferedReader br = new BufferedReader(new
InputStreamReader(System.in));
String str;
str = br.readLine();
- Reading Characters
No comments:
Post a Comment