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);
    }
}
Zabuzard
  • 25,064
  • 8
  • 58
  • 82
Jatin
  • 13
  • 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? – Zabuzard Oct 17 '17 at 02:20
  • 1
    As random [as this](https://xkcd.com/221/)? – shmosel Oct 17 '17 at 02: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`. – Zabuzard Oct 17 '17 at 02: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. – Jatin Oct 17 '17 at 08:53

2 Answers2

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.

tresf
  • 7,103
  • 6
  • 40
  • 101
0

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

Shubhendu Pramanik
  • 2,711
  • 2
  • 13
  • 23
  • 2
    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. – Tom Blodget Oct 17 '17 at 11:22