Scanner常用方法

Scanner用法

1.输入整数、字符串数组

第一行输入 n、m

第二行输入 n个整数

第三行输入 m个字符串

/**
 * 第一行输入n,m
 * 第二行输入n个整数
 * 第三行输入m个字符串
 */
public class MyScanner {

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

    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();
    }
    sc.close();
  }
}

2.输入二维数组

第一行输入 n、m

第二行开始输入二维数组

/**
 * 输入二维数组
 * 第一行输入n、m
 * 第二行开始输入二维数组
 */
public class MyScanner2 {
  public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);

    int n = sc.nextInt();
    int m = sc.nextInt();

    int[][] arr = new int[n][m];

    for (int i = 0; i < n; i++) {
      for (int j = 0; j < m; j++) {
        arr[i][j] = sc.nextInt();
      }
    }
    sc.close();
  }
}

3.输入字符串

输入字符串,用空格隔开

next( ) 和 nextLine( ) 的区别

next( ) :读取到空白停止,在读取输入后将光标放在同一行

nextLine( ) :读取到回车停止,在读取输入后将光标放在下一行

/**
 * 输入字符串,空格隔开
 */
public class MyScanner3 {
  public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);

    // next() 读取输入直到空格
    String s = sc.next();

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

    sc.close();
  }
}

4.输入字符串分割为数组

先用 nextLine( ) 读入字符串,再将字符串分割为字符数组或字符串数组

/**
     * 输入字符串分割为数组
     */
public class MyScanner4 {
  public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    String str;
    str = sc.nextLine();

    char[] c = new char[str.length()];
    for (int i = 0; i < str.length(); i++) {
      c[i] = str.charAt(i);
    }
    System.out.println(Arrays.toString(c));

    // 以空格分割字符串为数组
    String[] s = str.split(" ");
    System.out.println(Arrays.toString(s));
  }
}

5.换行输入数字和字符串

采用nextLine( ),将光标移到下一行。再继续读入字符串

第一行输入n,

第二行开始输入n行字符串,字符串中包含空格。

/**
   * 换行输入数字和字符串(包含空格)
   */
public class MyScanner5 {
  public static void main(String[] args) {

    Scanner sc = new Scanner(System.in);

    int n = sc.nextInt();
    String[] s = new String[n];

    for (int i = 0; i < n; i++) {
      String str = sc.nextLine();
      s[i] = str;
    }
    sc.close();
  }
}

  • 1
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值