初识加瓦

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

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

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值