JAVA---用户交互函数Scanner

用户交互Scanner

知识点概述

**1:**JAVA可以通过Scanner类来获取用户的输入(我的理解为相当于c语言中的接受字符函数,可以接受输入设备的输入)

2:基本语法:Scanner s =new Scanner (System.in);

3:通过Scanner类的next()与nextLine()方法获取输入的字符串,在读取前我们一般需要使用hasNext()和hasNextLine()判断是否还有输入的数据 (具体代码实现为 —if (scanner.hasNext())) 和 ----if (scanner.hasNextLine()) )

4: next():和nextLine()的区别:

next()对输入的字符中空格之前的内容都进行输出,但是当遇到空格时,立刻停止输出(例如输入hello kitty 输出结果为hello,因为hello后面有空格)。

nextLine()对输入的字符都进行输出

代码示例

使用next()输入:

package com.yuan.scanner;

import java.util.Scanner;

public class Demo01 {
    public static void main(String[] args) {
        //创建一个扫描器对象,用于接受键盘数据
        Scanner scanner = new Scanner(System.in);
        System.out.println("使用next方式接收  :");
        //判断用户有没有输入字符串
        if (scanner.hasNext()){
            //使用next方式接收
            String Str =scanner.next();//程序会等待用户输入完毕
            System.out.println("输出的内容为:  "+Str);

        }

        //凡是属于IO流的类如果不关闭会一直占用资源,要养成良好的习惯用完就关掉
        scanner.close();

    }
}


使用NextLine()输入:

package com.yuan.scanner;

import java.util.Scanner;

public class Demo02 {
    public static void main(String[] args) {
        Scanner scanner=new Scanner(System.in);//表示输入
        System.out.println("使用nextLine的方法接受:" );//提示你要输出了
        if (scanner.hasNextLine()){        //如果用户要输入字符串
            String Str  =scanner.nextLine()   ; //进行字符串的输入操作
            System.out.println("输出的内容为   "+Str);
        }
        scanner.close();
    }

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值