简体   繁体   中英

Not asking for second input

Code:

public class Adddemo {

    public static void main(String[] args) throws IOException {
        int i, j, k;
        System.out.println("enter value of i: ");
        i = (int) System.in.read();
        System.out.println("enter value of j: ");
        j = (int) System.in.read();

        k = i + 1;

        System.out.println("sum is: " + k);
    }
}

Is System.in.read used for multiple inputs?

System.in.read() is used to read a character.

suppose you enter 12, then i becomes 1(49 ASCII) and j becomes 2(50 ASCII) .

suppose you enter 1 and then press enter, i becomes (ASCII 49) and enter(ASCII 10) , even enter is considered a character and hence skipping your second input.

use a scanner or bufferedReader instead.

Using a scanner

Scanner sc = new Scanner(System.in);
int i = sc.nextInt();
int j = sc.nextInt();
int k = i + j; 
System.out.println(k);

Using a BufferedReader

BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
int i = Integer.parseInt(reader.readLine());
int j = Integer.parseInt(reader.readLine());
int k = i + j;
System.out.println(k);

System.in.read() doesn't read a number, it reads one byte and returns its value as an int.

If you enter a digit, you get back 48 + that digit because the digits 0 through 9 have the values 48 through 57 in the ASCII encoding.

To read a number from System.in you should use a Scanner.

use Scanner class instead:

 import java.util.Scanner;
 public class Adddemo {

    public static void main(String[] args) throws IOException {
        Scanner read=new Scanner(System.in);
        int i,j,k;
        System.out.println("enter value of i: ");
        i=(int)read.nextInt();
        System.out.println("enter value of j: ");
        j=(int)read.nextInt();

        k=i+1;

        System.out.println("sum is: "+k);
    }    
 }

System.in.read() reads 1 byte at a time.

if you want to feed your input values for i and j , do this
Leave one space between 1 and 2 while giving input in console
1 will be taken as value for i
2 will be taken as value for j

giving input as 12 (no spaces) will also yield the same result, cuz each byte is considered as an input

program
    int i,j;
        char c,d;
        System.out.println("enter value of i: ");
        i=(int)System.in.read();
        System.out.println("enter value of j: ");
        j=(int)System.in.read();

        System.out.println("i is: "+i);
        System.out.println("j is: "+j);

Output:
enter value of i,j: 
1 2          //leave one space 

i is: 1
j is: 2

let me know if you didn't understand yet

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