Java Scanner

Java中有一个类Scanner用于读取用户在命令行输入的信息。

Scanner类需要导入包java.util.Scanner

1
2
3
4
5
6
7
8
9
10
11
12
13
import java.util.Scanner;
 
public class MyClass {
 
     public static void main(String[] args) {
         // 创建一个scanner对象
         Scanner scanner =  new Scanner(system.in);
         System.out.println( "请输入一些字符" );
         // 读取用户输入的字符
         String value = scanner.nextLine();
         System.out.println( "您输入的字符是:" +value);
     }
}

nextLine()方法读取用户输入字符。Scanner还有其它方法

nextBigDecimal()
nextByte()
nextShort()
nextInt()
nextLong()
nextFloat()
nextDouble()
nextBoolean()

这些方法用于读取不同类型的数据。

有了Scanner类我们能做些人机交互程序,如猜数游戏:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
import java.util.Scanner;
 
public class MyClass {
 
     public static void main(String[] args) {
         // 创建一个scanner对象
         Scanner scanner =  new Scanner(system.in);
         // 生成一个随机
         int randomNumber = ( int )(Math.random()* 10 );
         System.out.println( "请输入你猜的数" );
         // 读取用户输入的数
         int value = scanner.nextInt();
 
         while (value!=randomNumber){
             System.out.println( "你输入是" +value+ ",目标数是:" +randomNumber+ ",再猜猜!" );
             // 重新生成随机
             randomNumber = ( int )(Math.random()* 10 );
             value = scanner.nextInt();
         }
 
         System.out.println( "恭喜你猜对了" );
     }
}

相关文章

HashMap是Java中最常用的集合类框架,也是Java语言中非常典型...
在EffectiveJava中的第 36条中建议 用 EnumSet 替代位字段,...
介绍 注解是JDK1.5版本开始引入的一个特性,用于对代码进行说...
介绍 LinkedList同时实现了List接口和Deque接口,也就是说它...
介绍 TreeSet和TreeMap在Java里有着相同的实现,前者仅仅是对...
HashMap为什么线程不安全 put的不安全 由于多线程对HashMap进...