zoukankan      html  css  js  c++  java
  • next(),nextInt(),nextLine()的区别

    next()、nextLine()、nextInt()作为scanner内置的方法,常常让人傻傻分不清楚,今天在这里记下他们的区别以及以此区别为出发点的用法:
    他们的区别在于对于空格的处理方式不同,以及返回值不同。
    使用nextLine()方法时,不将空格看做是两个字符串的间隔,而是看作字符串的一部分,返回时,它作为String类型一并返回:
    public class demo {

    public static void main(String args[]){

    Scanner sc=new Scanner(System.in);

    System.out.println("使用nextLine()方法,并且输入为:");

    String n=sc.nextLine();

    System.out.println("输出为:");

    System.out.println(n); }}结果如下:


    使用next()方法时,将空格看作是两个字符串的间隔:
    public class demo {

    public static void main(String args[]){

    Scanner sc=new Scanner(System.in);

    System.out.println("使用next()方法,将空格作为间隔符。输入为:");

    while(sc.hasNext()){ System.out.print("输出为:");

    String n=sc.next(); System.out.print(n);

    }

    } 运行结果如下:


    使用nextInt()方法时,与next()方法类似,只是它的返回值是int类型的,依旧将空格看作是两个输入的数据的间隔

    public class demo {

    public static void main(String args[]){

    Scanner sc=new Scanner(System.in);

    System.out.println("使用nextInt()方法,将空格作为间隔符。输入为:");

    while(sc.hasNext()){

    System.out.print("输出为:");

    int n=sc.nextInt();

    System.out.print(n);

    }

    }

    }此时程序的运行结果为:

    注意:当使用nexInt()方法时,只能输入int类型的数据。

  • 相关阅读:
    windows 根据端口查看进行PID 并杀掉进程
    Linux下安装mysql-5.7
    springcloud参考视频和源码笔记
    idea中配置热部署
    技术/方案实现目录
    系统功能设计产出模版
    JQuery点击行tr实现checkBox选中与未选中切换
    Java学习第一天
    ES6 记录
    微信小程序记录
  • 原文地址:https://www.cnblogs.com/Java60-123456/p/10654490.html
Copyright © 2011-2022 走看看