键盘录入


键盘录入

使用 Scanner 类(java.util.Scanner),有两套体系

  • 第一套体系
    • next 接收字符串
    • nextInt 接收整数
    • nextDouble 接收小数

遇到空格,制表符,回车就停止接收

  • 第二套体系
    • nextLine 接收字符串

可以接收空格,制表符,遇到回车才停止接收数据

第一、二套体系混用可能出现问题,例如先 nextInt ,再用 nextLine 。由于第一次输入整数后会加一个回车,会使第二个 nextLine 自动接收回车(换行符)而结束输入

Scanner scanner = new Scanner(System.in);//除了scanner为变量名外,其他固定
String str = scanner.nextLine(); //检测一行
String str = scanner.next();   //检测直到空格等
int sc = scanner.nextInt(); //检测一个int类型的数据

Author: havenochoice
Reprint policy: All articles in this blog are used except for special statements CC BY 4.0 reprint policy. If reproduced, please indicate source havenochoice !
评论
  TOC