Aashil
Aashil

Reputation: 437

Scanner reading from file instead of console

I am trying to evaluate postfix expression by fetching the expressions from a file using command "java PostFix < in.dat". Now when I want to fetch the value of a variable from the user(i.e console) it happens to be reading from the file and gives me Input Mismatch exception(as it reads string value from the file and not from the console). Below is the excerpt from my code. How can I fetch input from the console instead of the file?

public class PostFix{ 

    String operators[] = new String[]{"+","-","*","/","_","!","#","^","<","<=",">",">=","==","!=","&&","||","$"};
    ArrayList<String> variables = new ArrayList<String>();
    ArrayList<Integer> variable_value = new ArrayList<Integer>();

public static void main(String[] args) {
    // TODO Auto-generated method stub

    PostFix pf = new PostFix();
    pf.getVariables();

}

public void getVariables(){

    Scanner sc = new Scanner(System.in);
    String line = sc.nextLine();
    String tokens[] = line.split(" ");

    while(sc.hasNextLine()){
        System.out.println("in geVariables()");
        for(int i = 0; i < tokens.length; i++){

            if(!Arrays.asList(operators).contains(tokens[i])){

                try{
                Integer.parseInt(tokens[i]);    
                }
                catch(Exception e){
                    //e.printStackTrace();

                    variables.add(tokens[i]);
                    System.out.println("Please enter the value of "+tokens[i]);
                    variable_value.add(sc.nextInt());
                }

            }

        }

    }
    sc.close();     
    }   

}

Error:

Please enter the value of a
Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Unknown Source)
at java.util.Scanner.next(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
at PostFix.getVariables(PostFix.java:51)
at PostFix.main(PostFix.java:16)

Contents of in.dat file:

2 a + b _ * ! c c ^ 15 / # - $
value x + value y - != x y <= && $

Upvotes: 1

Views: 246

Answers (1)

PM 77-1
PM 77-1

Reputation: 13334

java PostFix < in.dat

means that all the standard input will be taken from in.dat file.

Your Java code does not know about this redirect. It simply reads from System.in (i.e. standard input), which often means keyboard.

So, the solution is to simple let your code run without any redirecting as

java PostFix

Upvotes: 1

Related Questions