user3956566
user3956566

Reputation:

Strange return value when asking for int input

I have the following code:

import java.io.*;

public class ExamPrep2
{
    public static int getPositiveInt() 
    {

    BufferedReader stdin = new BufferedReader(
            new InputStreamReader(System.in));

    int positiveInt = 0;

    try
    {
        positiveInt = stdin.read();
        if (positiveInt < 0) {
            System.out.print("A negative int! -1");
            return -1;
        }
        else {
            System.out.print("Yay! " + positiveInt);
            return positiveInt;
        }
    }
    catch (IOException e)   {
        System.out.print("Positive int is NaN! -2");
        return -2;
        }
    }

    public static void main(String[] args)
    {
        System.out.print("Enter a positive integer:");
        getPositiveInt();
    }
}

But when I enter in values, I am not getting the same value back that I have entered.

eg:

Enter a positive integer:1
Yay! 49
Enter a positive integer:-2
Yay! 45  
Enter a positive integer:x
Yay! 120

What obvious thing am I overlooking?

Upvotes: 0

Views: 102

Answers (4)

Jeroen Vannevel
Jeroen Vannevel

Reputation: 44448

You are reading everything in as a char:

positiveInt = stdin.read();

This will return a char. When you enter 1 it will return the ASCII value of this character. Which is 49.

Instead you should use a Scanner.

Scanner scan = new Scanner(System.in);
int input = scan.nextInt();

See the following sample:

public static void main(String[] args) {
    char input = '1';
    System.out.println((int) input);
}

Output:

49

Upvotes: 3

Masudul
Masudul

Reputation: 21971

The method stdin.read(); is not right method to get int value. Use stdin.readLine(),

  positiveInt = Integer.parseInt(stdin.readLine());

Upvotes: 3

umhelp
umhelp

Reputation: 175

This line of code is reading a single character from the stream so it is reading "-" and interrupting it as an integer which is going to be > 0.

positiveInt = stdin.read();

You will need to read the full line of text to get both the - and the 1 characters from the stream.

You can look at an ASCII table and see that 1 = ASCII 49, - is ASCII 45, etc...

http://www.asciitable.com/

Upvotes: 3

Prasad Kharkar
Prasad Kharkar

Reputation: 13566

Read it using Scanner class. Scanner scanner = new Scanner(System.in); and then scanner.nextInt(). BufferedReader is giving you the ASCII value.

Upvotes: 2

Related Questions