Java中的控制台输入Scanner和BufferedReader以及Scanner中的nextLine()和next的问题。

Java中的控制台输出

java中常用的控制台的输入有ScannerBufferedReade两个。

Scanner的使用如下所示:

import.java.util.Scanner;
// An highlighted block
Scanner scan = new Scanner(System.in);
String str=scan.readline();
//

BufferedReader的使用如下所示:

import.java.io.BufferedReader;
// An highlighted block
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String read=br.readline();
//

我们接着说Scanner使用中的问题:

其中Scanner中有很多的方法,比如:readline();nextInt();next()等等。其中的方法具体查阅API查看吧。
接下首先是大家共所周知的区别

nextLine()方法返回的是Enter键之前的所有字符,可以得到带空格的字符串的。

next()会自动消去有效字符前的空格,只返回输入的字符,不能得到带空格的字符串。

然而!

next()在输入有效字符之后,将其后输入的空格键、Tab键或Enter键等视为分隔符或结束符。

nextLine()方法的结束符只是Enter键

因此!

nextLine()自动读取了被next()去掉的Enter作为他的结束符,所以没办法从键盘输入值。

经过验证,其他的next的方法,如nextDouble() ,nextFloat() ,nextInt() 等与nextLine()连用时都存在这个问题。

具体点就是nextLine()不能用在nextInt()的后面!!!!

解决方法有两种

第一种

在每一个 next()、nextDouble() 、nextFloat()、nextInt() 等语句之后加一个nextLine()语句,将被next()去掉的Enter结束符过滤掉。

第二种

把nextLine()改为next()

例如如下代码:

//part1
        Scanner sc = new Scanner(System.in);
        int n=sc.nextInt();
        sc.nextLine();//这里不加nextLine()就会出问题
        int x[]=new int[n];
        int y[]=new int[n];
        for(int i=0;i<n;i++){
            String b = sc.nextLine();
            String c[]=b.split(",");
            x[i]=Integer.parseInt(c[0]);
            y[i]=Integer.parseInt(c[1]);
 
        }
//part2
        Scanner sc = new Scanner(System.in);
        int n=sc.nextInt(); 
        int x[]=new int[n];
        int y[]=new int[n];
        for(int i=0;i<n;i++){
            String b = sc.next();//这里用next()就可以了
            String c[]=b.split(",");
            x[i]=Integer.parseInt(c[0]);
            y[i]=Integer.parseInt(c[1]);
 
        }

这一段的原文:https://blog.csdn.net/guanghuichenshao/article/details/81545450

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值