欢迎您访问 最编程 本站为您分享编程语言代码,编程技术文章!
您现在的位置是: 首页

java 输入扫描仪的基本用法

最编程 2024-04-28 17:10:18
...

1.基本介绍

java.util.Scanner 是 Java5 的新特征,我们可以通过 Scanner 类来获取用户的输入,每个next获取输入对应的字符。

Scanner sc = new Scanner(System.in);

当我们通过 Scanner 类的 next()  nextLine() 方法获取输入的字符串,在读取前我们一般需要 使用hasNext 与 hasNextLine 判断是否还有输入的数据

  • next() -->hasNext()
  • nextLine() ---->hasNextLine()

2.使用举例 

hasNext和next测试

public static  void main(String[] args){
        Scanner scanner = new Scanner(System.in);
        System.out.println("请输入:");
        if (scanner.hasNext())
            System.out.println("输出:"+scanner.next());
        scanner.close();
    }
请输入:
测试一下   哈哈
输出:测试一下

hasNextLine和nextLine

public static  void main(String[] args){
        Scanner scanner = new Scanner(System.in);
        System.out.println("请输入:");
        if (scanner.hasNextLine())
            System.out.println("输出:"+scanner.nextLine());
        scanner.close();
    }
请输入:
测试一下   哈哈哈
输出:测试一下   哈哈哈

两者比较:

很明显,从结果来看,next获取下一个字符串,输入间隔为空格或回车时截断,而nextLine则是获取一行数据。

next():

  • 一定要读取到有效字符后才可以结束输入。
  • 对输入有效字符之前遇到的空白,next() 方法会自动将其去掉。
  • 只有输入有效字符后才将其后面输入的空白作为分隔符或者结束符。
  • next() 不能得到带有空格的字符串。

nextLine():

  • 以Enter为结束符,也就是说 nextLine()方法返回输入回车之前的所有字符
  • 可以获得空白。
     

3.常用方式

scanner.nextLine().trim();//去掉输入两端的空格
String[] arrStr = scanner.nextLine().trim().split(" ");//将输入的一行按照空格拆分为数组


while (scanner.hasNextLine()){
            int len = Integer.parseInt(scanner.nextLine().trim());
            int[] arrInt = new int[len];
            String[] contentStr = scanner.nextLine().trim().split(" ");
            int i =0;
            for (String content:contentStr){
                arrInt[i++] = Integer.parseInt(content);
            }
    System.exit(0);
}

其他的获取输入方式:

hasNext()----next()

hasNextInt()----nextInt()

hasNextBoolean----nextBoolean()

hasNextByte()----nextByte()

hasNextShort()----nextShort()

hasNextInt()----nextInt()

hasNextLong()----nextLong()

hasNextFloat()----nextFloat()

hasNextDouble()----nextDouble()

hasNextBigInteger()----nextBigInteger()

hasNextBigDecimal()----nextBigDecimal()

4.while循环输入scanner如何退出?

以下三种退出方式:

while (!scanner.hasNext("0") ){
//标志位退出
}
  while (scanner.hasNextLine() ){
//            代码段
            if(scanner.hasNext("0"))//内部标志退出
                break;
        }
  while (scanner.hasNextLine() ){
        //    代码段
           System.exit(0);//系统退出

        }
 

推荐阅读