一, Scanner
需要用到从控制台输入数据时, 使用 Scanner 类.
? ?
二, 使用 Scanner 读取整数
注意: 使用 Scanner 类, 需要在最前面加上
importjava.util.Scanner; |
表示导入这个类, 才能够正常使用
导入类的语法:
import 类的包名; |
? ?
? ?
importjava.util.Scanner; ? ? public classHelloWorld { ????public staticvoidmain(String[] args) { ????????Scanner s = newScanner(System.in); ????????inta = s.nextInt(); ????????System.out.println("第一个整数:"+a); ????????intb = s.nextInt(); ????????System.out.println("第二个整数:"+b); ????} } |
? ?
三, 使用 Scanner 读取浮点数
? ?
importjava.util.Scanner; ?? ? public classHelloWorld { ????public staticvoidmain(String[] args) { ????????Scanner s = newScanner(System.in); ????????floata = s.nextFloat(); ????????System.out.println("读取的浮点数的值是:"+a); ????} } |
? ?
四, 使用 Scanner 读取字符串
? ?
importjava.util.Scanner; ?? ? public classHelloWorld { ????public staticvoidmain(String[] args) { ????????Scanner s = newScanner(System.in); ????????String a = s.nextLine(); ????????System.out.println("读取的字符串是:"+a); ????} } |
? ?
五, 读取整数后, 接着读取字符串
需要注意的是, 如果在通过 nextInt() 读取了整数后, 再接着读取字符串, 读出来的是回车换行:"\r\n", 因为 nextInt 仅仅读取数字信息, 而不会读取回车换行 "\r\n".
? ?
所以, 如果在业务上需要读取了整数后, 接着读取字符串, 那么就应该连续执行两次 nextLine(), 第一次是取走回车换行, 第二次才是读取真正的字符串
? ?
importjava.util.Scanner; ?? ? public classHelloWorld { ????public staticvoidmain(String[] args) { ????????Scanner s = newScanner(System.in); ????????inti = s.nextInt(); ????????System.out.println("读取的整数是"+ i); ????????String rn = s.nextLine(); ????????String a = s.nextLine(); ????????System.out.println("读取的字符串是:"+a); ????} } |
? ?
? ?
??
来源: http://www.bubuko.com/infodetail-3035694.html