QUESTIONS & ANSWERS

How to accept different types of inputs in a line by using InputStreamReader() and StringTokenizer() in Java?

o read different types of inputs in a line using InputStreamReader and StringTokenizer in Java, you can follow these steps:

  1. Create an InputStreamReader object to read input from the keyboard.
  2. Create a BufferedReader object to read a line of input from the keyboard.
  3. Create a StringTokenizer object to tokenize the input line.
  4. Use the nextToken() method of the StringTokenizer object to read each token as a string.
  5. Convert each token to the appropriate data type using the appropriate parse method.

Here's an example that reads an integer, a floating-point number, and a string from a line of input using InputStreamReader and StringTokenizer:

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.StringTokenizer;

public class Main {
  public static void main(String[] args) {
    try {
      InputStreamReader isr = new InputStreamReader(System.in);
      BufferedReader br = new BufferedReader(isr);

      String inputLine = br.readLine();
      StringTokenizer st = new StringTokenizer(inputLine);

      int a = Integer.parseInt(st.nextToken());
      double b = Double.parseDouble(st.nextToken());
      String c = st.nextToken();

      System.out.println("a = " + a);
      System.out.println("b = " + b);
      System.out.println("c = " + c);

    } catch (Exception e) {
      e.printStackTrace();
    }
  }
}

In this example, we first create an InputStreamReader object to read input from the keyboard and wrap it with a BufferedReader object to read a line of input. We then create a StringTokenizer object and pass the input line to its constructor. We use the nextToken() method to read each token as a string, and then parse it to the appropriate data type using the parseInt() and parseDouble() methods. Finally, we print out the values that were read.

Note that you should handle exceptions when reading input from the keyboard, as shown in the example. Additionally, you may need to modify the code to handle different input formats or different numbers of tokens.

06/03/2023, 11:14 am Read : 320 times