robertszasz
robertszasz

Reputation: 3

Input does not behave like expected, java FileReader

I have the following code which when executed should get an input integer from the specified file and output the multiplication table up to 10 with the number given.

Right now I do not know why but when reading the number it converts it to something totally different.

Input was 3 and the file recognized num as 51.

Any good guesses what is going on and I am not seeing?

public class exercise2 {
    public static void main(String[] args) {
        try {
            FileReader reader = new FileReader("e://ex2.txt");
            int num = reader.read();
            for (int i=0; i<11; i++){
                System.out.println(num + " * " + i+ "= "+ num*i);
            }
            reader.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Upvotes: 0

Views: 31

Answers (2)

cbley
cbley

Reputation: 4608

Look at the docs:

https://docs.oracle.com/javase/7/docs/api/java/io/InputStreamReader.html#read()

Reads a single character.

So, this method simply returns the first character of your file (cast to an int).

What you want is to use a Scanner since you want to parse the file:

Scanner s = new Scanner(new File("e://ex2.txt"));

int input = s.nextInt();

Upvotes: 1

Joachim Sauer
Joachim Sauer

Reputation: 308001

Reader.read reads a single character.

The character 3 has the Unicode codepoint 51 (decimal).

Upvotes: 3

Related Questions