简体   繁体   中英

Difference in the output when a value is given in the program and when user input is given

public class ForComma {
    public static void main(String args[]) throws java.io.IOException {
        System.out.println("enter j");
        int j = (int) System.in.read();
        for(int i=0; i<j ; j--, i++){
            System.out.println("i is " + i + "\tj is " + j);
        }
    }
}

In the for-loop , when j is defined as j=10 , the result is different with the result when 10 is entered as an user input. Why?

It is because you are using System.in.read() to get value from console.

It will actually read next byte of data, which in your case is 1 as ascii code ie 49

Just replace your code with this:

for(i=0,j=Integer.parseInt(System.in.readLine());i<j;j--,i++){

You are using System.in.read() to read user input and it is wrong.

When input is given to the console, it will be given to our software as a Stream . Streams are special. They don't give everything once. They give the values you entered in the console, character by character.

If you enter 10 in the console and when you press enter key the characters will be given to the Stream. Once you call read() , 49 will be given as the output(As 49 is the ASCII value of 1). The next time you call read() , 48 will be given as the output(As 48 is the ASCII value of 0). The next time you call read() , 13 will be given as the output(As 13 is the ASCII value of enter key).

So, you will have to read all those 3 bytes in order to determine the value the user enter. But you don't need to worry. Java has classes where this task is done and we just have to call the needed method.

import java.util.Scanner;
public class ForComma {
    public static void main(String args[]) throws java.io.IOException {
        System.out.print("Enter j: ");
        Scanner s = new Scanner(System.in);
        int j = s.nextInt();
        for (int i = 0; i < j; j--, i++) {
            System.out.println("i is " + i + "\tj is " + j);
        }
    }
}

System.in.read doku:

Reads 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. This method blocks until input data is available, the end of the stream is detected, or an exception is thrown. A subclass must provide an implementation of this method.

So what happens? System.in.read actually reads the input, but just the next chunk of byte. In fact for the input 10 this is just the one. This results in an int value of 49 .

If you parse this value to a char then you will notice that you got the ascii representation of the char 1 and not the int value for the number 10 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM