Java:Scanner

这篇博客详细介绍了Java中Scanner类的使用,包括如何读取int类型和String类型的数据,以及next()和nextLine()的区别。示例代码展示了在多行输入和循环读取时的运用,帮助理解Scanner在处理用户输入时的不同方法。
摘要由CSDN通过智能技术生成

两者都是以空格作为结束标记!!!

   int等基本类型的数组使用sc.nextInt()

   Sting类型的使用sc.next() 

public class MyScanner {

    public static void main(String[] args) {
        //创建对象
        Scanner sc = new Scanner(System.in);
        System.out.println("输入数据:");
        //多行输入
        int n = sc.nextInt();
        int m = sc.nextInt();
        int[] arr = new int[n];
        String[] str = new String[m];

        //int等基本数据类型的数组,用nextInt(),同行或不同都可以
        for(int i=0; i<n; i++) {
            arr[i] = sc.nextInt();
        }
        //String字符串数组, 读取用next(),以空格划分
        for(int i=0; i<m; i++) {
            str[i] = sc.next();
        }

        //调用方法进行操作
        TestSc(n, m, arr);
        TestStr(str);

        System.out.println("Test01 End");

        //关闭
        sc.close();
    }

    public static void TestSc(int n, int m, int[] arr) {
        System.out.println("数据n:" + n + ", 数据m:" + m);
        System.out.println(Arrays.toString(arr));
    }

    public static void TestStr(String[] str) {
        System.out.println(Arrays.toString(str));
    }

next:碰到空格停止

nextLine:碰到回车停止 

public static void main(String[] args) {

        Scanner sc = new Scanner(System.in);
        System.out.println("输入字符串:");

        //next():只读取输入直到空格。
        String str = sc.next();

        //nextLine():读取输入,包括单词之间的空格和除回车以外的所有符号
        String str2 = sc.nextLine();

        System.out.println("str:" + str);
        System.out.println("str2:" + str2);

        //关闭
        sc.close();
    }

不能用for的情况下

while(sc.hasNext()):循环读取 

 public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);

        while(sc.hasNext()) {
            int n = sc.nextInt();
            String str = sc.next();
            Tes(n, str);
        }

        sc.close();
    }

    public static void Tes(int n, String str) {
        System.out.println("n = " + n);
        System.out.println("str = " + str);
        System.out.println("str.length = " + str.length());
    }

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值