1

I am trying to execute this code but its giving me random values everytime:

Output:

Output

Code:

public class Temp  {
    static int x;
    static {
        try {
            x = System.in.read();
        } catch (IOException ex) {
            System.out.println(ex);
        }
    }
}


class TempA {
    public static void main(String[] args) {
        System.out.println(Temp.x);
    }
}
4
  • 2
    What do you mean by random values? Can you give an example? Are you typing something into your keyboard while running the program? Commented Oct 17, 2017 at 2:20
  • 1
    As random as this? Commented Oct 17, 2017 at 2:21
  • Usually System.in.read() returns the next byte currently stored in System.in. This object usually is connected to your standard input, the console for example. So if your typing something into the keyboard it will get stored there. So I would assume that if you type in 5 it will also print 5. Commented Oct 17, 2017 at 2:25
  • @Zabuza Suppose I type 23 as input, it gives me 50 as output. Yes, I am typing something on my keyboard while running the program. Commented Oct 17, 2017 at 8:53

2 Answers 2

1

The values aren't random, they're:

[...] the next byte of data from the input stream. The value byte is returned as an int in the range 0 to 255. If no byte is available because the end of the stream has been reached, the value -1 is returned. http://docs.oracle.com/javase/7/docs/api/java/io/InputStream.html#read()

This means if you type a and hit Enter you'll get 97.

If you're looking for content of what was typed (and not the raw byte value) you'll need to make some changes... The easiest way it to use the Scanner class. Here's how you get a numerical value:

import java.util.Scanner;

public class Temp  {
    static int x;
    static {
        Scanner sc = new Scanner(System.in);
        x = sc.nextInt();
    }
}


class TempA {
    public static void main(String[] args) {
        System.out.println(Temp.x);
    }
}

See also System.in.read() method.

Sign up to request clarification or add additional context in comments.

Comments

0

This is because it is returnung the ASCII value of the first digit/character of your input.

1 Comment

Well, not ASCII and not value in general, but the next byte of whatever the stream is supplying. Given that the System.in stream is typically being feed from the console/shell, it is usually typed text. There is no text but encoded text. The shell is using whatever character encoding it is using, and that's typically UTF-8, or CP437 or similar, not ASCII. Go locale or chcp to find yours.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.