初识加瓦

来源:互联网 发布:卫夫人知乎 编辑:程序博客网 时间:2024/04/29 10:23

Hello World的程序就不记了,太EASY了。

试着写了个A + B problem的程序,就遇到了个问题。怎么读整数呢?System.in.read不行,难道要一个一个读字符再自己做转换?不会吧,那也太麻烦了。再想想别的办法,翻了翻文档,挑了一个java.io.DataInputStream,用方法readInt试了一下,还是不行:

readInt

 public final int readInt() throws IOException
从当前数据输入流中读取一个有符号的 32 位整数。 此方法从基本输入流中读入四个字节。 如果读入的字节,顺序为 b1b2,b3b4, 满足 0 <= b1, b2,b3,b4 <= 255, 那么结果等于:
    (b1 << 24) | (b2 << 16) + (b3 << 8) +b4

该方法将一直阻塞,直到此四个字节数据被读入,或检测到了数据流尾或抛出异常。

返回值:
当前输入流的下四个字节,解释为一个 int
抛出: EOFException
如果在读入四个字节前到达了文件尾。
抛出: IOException
如果发生某个 I/O 错误。

大名鼎鼎的加瓦不会连读个数都这么不方便吧?继续找文档,在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
Throws:
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

下面是完整的程序:

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

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

嘿嘿,我的第一个加瓦程序,志之^_^

至于加瓦其它的那么多特性,以后慢慢体验吧!

原创粉丝点击