I am trying to use scanner class by passing java.io.InputStream variable

70 views Asked by At

A question from core java. I am trying to use scanner class by passing java.io.InputStream variable just like System.in. I dissemble java.io.System class and I found that a field is declared as "public static final java.io.InputStream in;" so I also declared a filed of same type as "myin". but it is giving compile time error stating that - error:variable myin might not have been initialized. I just wanted to know how can I declared "in" and "out" variable of my own. Please help me out. any help will be highly appreciated.

import java.util.Scanner;
import java.io.*;
class Test
{
  public static final java.io.InputStream myin;
 public static void main(String[] args)
 {
    int i;  
    Scanner sc = new Scanner(Test.myin);
    System.out.println("Enter a number:");
    i = sc.nextInt();
    System.out.println(i);  
 } 
}
1

There are 1 answers

5
Konrad Höffner On

The final modifier means that the variable has to be initialized exactly once, but you don't initialize it at all. However in your case, the variable is not needed, you can initialize the Scanner with Scanner sc = new Scanner(System.in);.