不要求第二次输入

时间:2015-06-11 12:45:41

标签: java

代码:

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);
    }
}

System.in.read是否用于多个输入?

4 个答案:

答案 0 :(得分:3)

System.in.read()用于读取角色。

假设您输入12,则i变为1(49 ASCII)j变为2(50 ASCII)

假设您输入1然后按Enter键,i变为(ASCII 49)enter(ASCII 10),即使输入也被视为字符,因此会跳过您的第二个输入。

改为使用scannerbufferedReader

使用扫描仪

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

使用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);

答案 1 :(得分:1)

System.in.read()没有读取数字,它读取一个字节并将其值作为int返回。

如果输入一个数字,则会返回48 +该数字,因为数字0到9的ASCII编码值为48到57.

要从System.in读取数字,您应该使用扫描仪。

答案 2 :(得分:0)

改为使用Scanner类:

 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);
    }    
 }

答案 3 :(得分:0)

System.in.read()一次读取1个字节。

如果要输入i和j的输入值,请执行此操作 在控制台中输入输入时,在1和2之间留一个空格 1将被视为i的值 2将被视为j

的值

将输入设为12(无空格)也会产生相同的结果,因为每个字节都被视为输入

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

如果你还不明白,请告诉我

相关问题