简体   繁体   English

System.in.read() 方法

[英]System.in.read() method

Following is the code, I have written to get two inputs from user.以下是我编写的代码,用于从用户那里获取两个输入。 But when I run the program, It takes only one input and generate other by itself and calculate the wrong value.但是当我运行程序时,它只需要一个输入并自行生成另一个并计算错误的值。 please help.请帮忙。 Thanks谢谢

import java.io.IOException;
import java.util.*;

class ThrowsExcpt {
    int divide(int x, int y) throws ArithmeticException, IOException {
        return x / y;
    }
}

class ThrowsTemps {
    public static void main(String s[]) throws IOException {

        int x = System.in.read();
        int y = System.in.read();

        ThrowsExcpt th = new ThrowsExcpt();
        int r = th.divide(x, y);
        System.out.println(r);
    }
}

System.in is an InputStream - read() reads exactly one byte. System.in是一个InputStream - read()恰好读取一个字节。 Your direct input is more than one byte and so both values are directly read within the first input. 您的直接输入超过一个字节,因此两个值都将在第一个输入中直接读取。

Use a Scanner instead (with System.in as Input): 改用扫描仪(将System.in作为输入):

 Scanner sc = new Scanner(System.in);
 int i = sc.nextInt();

More Examples: http://docs.oracle.com/javase/1.5.0/docs/api/java/util/Scanner.html 更多示例: http : //docs.oracle.com/javase/1.5.0/docs/api/java/util/Scanner.html

Try using a Scanner object to read your user's input : 尝试使用Scanner对象读取用户的输入:

Scanner scanner = new Scanner(System.in);
int x = scanner.nextInt();

Read() method. Read()方法。

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. 值字节以int形式返回,范围为0到255。如果由于到达流的末尾而没有字节可用,则返回值-1。 This method blocks until input data is available, the end of the stream is detected, or an exception is thrown. 此方法将阻塞,直到可用输入数据,检测到流的末尾或引发异常为止。

from http://docs.oracle.com/javase/7/docs/api/java/io/InputStream.html#read%28%29 . 来自http://docs.oracle.com/javase/7/docs/api/java/io/InputStream.html#read%28%29

So use scanner for this. 因此,为此使用scanner

And according to your question Why is it not asking for second input? 并根据您的问题, 为什么不要求第二次输入? Reason is read() method wait for input source once it gets the input it takes the byte by byte from that input source. 原因是read()方法等待输入源获得输入后,才从该输入源中逐字节读取。 For ex: 例如:

        inChar = System.in.read();
        i = System.in.read();
        i1 = System.in.read();
        System.out.print("You entered ");
        System.out.println(inChar);
        System.out.println(i);
        System.out.println(i1);

you enter abc as input then you will get 输入abc作为输入,您将获得

Enter a Character:
abc
You entered 97
98
99

as out put which is byte values of a,b and c . 输出结果是a,b和c的字节值。

Explanation: input abc byte array 说明:输入abc字节数组

+--------------------+
| 97 | 98 | 99 | other byte value for **Enter**
+--------------------+ 

first System.in.read() will get first index of array, second one will get second and so on. 第一个System.in.read()将获取数组的第一个索引,第二个将获取第二个索引,依此类推。

Why unwanted assignment is occuring? 为什么会发生不必要的分配?

The keyboard input character(s) is stored in input buffer after ENTER is pressed. 按下ENTER后,键盘输入字符将存储在输入缓冲区中。 ENTER includes line feed '\\n' in the input character. ENTER在输入字符中包含换行符'\\ n'。 Decimal/integer value of line feed '\\n' is 10. 换行符'\\ n'的十进制/整数值为10。

System.in.read() reads only first one character from the input character(s), the character is casted into integer and return it. System.in.read()仅从输入字符中读取第一个字符,然后将该字符转换为整数并返回。 And that character will be excluded from the input buffer. 并且该字符将从输入缓冲区中排除。

The rest of the characters are still pending in the input buffer until it is read by System.in.read() in the same manner stated above. 其余字符仍在输入缓冲区中挂起,直到由System.in.read()以上述相同的方式读取为止。

    int inputchar1, inputchar2, inputchar3;

    System.out.print("input: ");// input: 43

    // The line feed '\n' is generated when ENTER is pressed.
    // '4', '3' and '\n' are in the input buffer.

    inputchar1 = System.in.read(); // '4' is read and returns 52 (corresponding integer value)
    // '3' and '\n' is in the input buffer.

    inputchar2 = System.in.read(); // '3' is read and returns 51
    // '\n' is pending in the input buffer.

    inputchar3 = System.in.read(); // '\n' is read and returns 10
    // no more input character in the input buffer.

    System.out.println("inp1 =" + inputchar1);
    System.out.println("inp1 =" + inputchar2);
    System.out.println("inp1 =" + inputchar3);

    /*
     * Refer to ASCII table for char to decimal conversion.
     * Although java Char is 16-bit unicode ASCII is still applicable.
     */

How to avoid unwanted assignment? 如何避免不必要的分配?

Keep reading the content of input buffer until it gets depleted. 继续读取输入缓冲区的内容,直到耗尽为止。

int x, y, avoid;

System.out.println("Enter x: ");
x = System.in.read();
// Reading all the characters after the first character so that
// no character stays pending in the input buffer.
do {
    avoid = System.in.read();
} while(avoid != '\n');

System.out.println("Enter y: ");
// New input buffer is created.
y = System.in.read();
do {
    avoid = System.in.read();
} while(avoid != '\n');

Reference: "Java: A beginner's guide 6e" - Herbert Schildt 参考:“ Java:初学者指南6e”-Herbert Schildt

If you are using the console, try this: 如果使用控制台,请尝试以下操作:

int x = Integer.parseInt(System.console().readLine());
int y = Integer.parseInt(System.console().readLine());

hey bro this should work for what you need i think if its not let me know 嘿兄弟这应该为您需要的工作我想如果它不让我知道

import java.io.IOException;
import java.util.Scanner;

public class noob{


class ThrowsExcpt {
    int divide(int x, int y) throws ArithmeticException, IOException {
        return x / y;
    }
}

class ThrowsTemps {
    public void main(String s[]) throws IOException {
Scanner sc = new Scanner(System.in);
System.out.println("Enter number 1");
        int x = sc.nextInt();
 System.out.println("Enter number 2");
        int y = sc.nextInt();

simply put - 简单的说 -

int x = System.in.read();

automatically throws an exception. 自动引发异常。

  • you allocated and defined a memory cell to hold an int, then assigned a byte to be stored there. 您分配并定义了一个存储单元来保存一个int,然后分配了一个要存储在其中的字节。 Recast the input or use a diff. 重铸输入或使用差异。 input method. 输入法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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