大家好,欢迎来到IT知识分享网。
Hello World的程序就不记了,太EASY了。
试着写了个A + B problem的程序,就遇到了个问题。怎么读整数呢?System.in.read不行,难道要一个一个读字符再自己做转换?不会吧,那也太麻烦了。再想想别的办法,翻了翻文档,挑了一个java.io.DataInputStream,用方法readInt试了一下,还是不行:
readInt
public final int readInt() throws IOException
-
从当前数据输入流中读取一个有符号的 32 位整数。 此方法从基本输入流中读入四个字节。 如果读入的字节,顺序为
b1
,
b2
,
b3
和
b4
, 满足
0 <= b1, b2,b3,b4 <= 255
, 那么结果等于:(b1 << 24) | (b2 << 16) + (b3 << 8) +b4
该方法将一直阻塞,直到此四个字节数据被读入,或检测到了数据流尾或抛出异常。
-
-
返回值:
-
当前输入流的下四个字节,解释为一个
int
。 - 如果在读入四个字节前到达了文件尾。
- 如果发生某个 I/O 错误。
抛出: EOFException
抛出: IOException
-
当前输入流的下四个字节,解释为一个
大名鼎鼎的加瓦不会连读个数都这么不方便吧?继续找文档,在util里找到了一个叫Scanner的类,用它的nextInt方法,hoho,这会就对了嘛。
nextInt
public int nextInt()
-
Scans the next token of the input as an
int.An invocation of this method of the form nextInt() behaves in exactly the same way as the invocation nextInt(radix), where
radix
is the default radix of this scanner. -
-
-
Returns:
-
the
int scanned from the input -
InputMismatchException
– if the next token does not match the
Integer regular expression, or is out of range -
NoSuchElementException
– if input is exhausted -
IllegalStateException
– if this scanner is closed
Throws:
-
the
下面是完整的程序:
public class Main {
public static void main(String args[]) {
int a, b;
try {
Scanner in = new Scanner(System.in);
a = in.nextInt();
b = in.nextInt();
System.out.println(a + b);
}
catch (Exception e) {}
}
}
嘿嘿,我的第一个加瓦程序,志之^_^
至于加瓦其它的那么多特性,以后慢慢体验吧!
免责声明:本站所有文章内容,图片,视频等均是来源于用户投稿和互联网及文摘转载整编而成,不代表本站观点,不承担相关法律责任。其著作权各归其原作者或其出版社所有。如发现本站有涉嫌抄袭侵权/违法违规的内容,侵犯到您的权益,请在线联系站长,一经查实,本站将立刻删除。 本文来自网络,若有侵权,请联系删除,如若转载,请注明出处:https://haidsoft.com/150048.html