关于java的标准输入在刷题时的应用nextInt,nextLine,nextDouble

就是在刷题网站上想要读取多行应该怎么做?

 想要读取这四行数据,最简单的方法是使用nextLine()函数每次读一行数据,注意这个函数读取的是String数据,一般刷题网站给的也是String数据,后面根据需要在进行数据类型转换。

import java.util.Scanner;
public class Main
{
    public static void main(String[] args)
    {
        Scanner in=new Scanner(System.in);
        String tempstr=in.nextLine();
        int num=Integer.valueOf(tempstr);
        String str=in.nextLine();
        String str1=in.nextLine();
        String str2=in.nextLine();
        System.out.println(num);
        System.out.println(str);
        System.out.println(str1);
        System.out.println(str2);
        
        
    }

}

读取的结果进行打印后的效果:

当然还有一些其他的读取方式:

例如nextInt,nextDouble,nextFloat等等类似于Next+基本数据类型的读取方式

这些方式读取之后,每次只读取一个基本数据类型的变量,遇到空格和回车后会自动停止,如果是空格就调用nextInt就可以跳过空格,来读取下一个值,如果是回车那么用nextLine来读取这个回车才能进行下一行操作

输入是:

 代码为

import java.util.Scanner;
public class Main
{
    public static void main(String[] args)
    {
        Scanner in=new Scanner(System.in);
        int num =in.nextInt();
        int num1 =in.nextInt();
        int num2 =in.nextInt();
        String str=in.nextLine();
        String str1=in.nextLine();
        String str2=in.nextLine();
        System.out.println(num);
        System.out.println(num1);
        System.out.println(num2);
        System.out.println(str);
        System.out.println(str1);
        System.out.println(str2);
        
        
    }

}

输出为

这个例子说明nextInt可以把下一个空格给拿掉,但是却不能拿掉下一个回车,因此需要在使用完nextInt之后需要使用一个nextLine来吃掉这个多余的空格。

代码实际输出为

3
4
5
helloo
helllo
这样就成功的读取了

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值