java中next()、nextInt()和nextLine()的区别

看一下官方解释:

nextInt(): it only reads the int value, nextInt() places the cursor in the same line after reading the input.

next(): read the input only till the space. It can't read two words separated by space. Also, next() places the cursor in the same line after reading the input.

nextLine():  reads input including space between the words (that is, it reads till the end of line \n). Once the input is read, nextLine() positions the cursor in the next line.

其实最容易出错的就是红色那部分,今天我在编写代码的时候发现了这个问题,先输入整型数据,紧接着再输入字符串型数据,会出现整型数据输入完后敲回车直接略过字符串输入的问题,这种现象的原因正是上面所说的三者区别。

import java.util.*;
public class Circle
{
	double radius;
	String color;
	public static void main(String[] args){
		Scanner s = new Scanner(System.in);
		System.out.print("请输入半径:");
		double r = s.nextDouble();
		System.out.print("请输入圆的颜色:");
		String n = s.nextLine();
		Circle c = new Circle(r , n);
		System.out.println("圆形的颜色为:" + c.color);
		System.out.println("圆形的面积为:" + area(r) + " " + "," + " " + "圆形的周长为:" + perimeter(r));

	}
	public Circle(){
	}
	public Circle(double i , String c){
		radius = i;
		color = c;
	}
	public static double area(double n){
		return 3.14 * n * n;
	}
	public static double perimeter(double n){
		return 3.14 * 2 * n;
	}
}

注意这个代码上面next()和nextLine()的顺序,这样输入会有下面问题:

出现这种问题的原因简单来说,就是:

  • next()不会吸取字符前/后的空格/Tab键,只吸取字符,开始吸取字符(字符前后不算)直到遇到空格/Tab键/回车截止吸取;
  • nextLine()吸取字符前后的空格/Tab键,回车键截止。

其实就是说:nextLine吸收了next后的回车,直接跳过输入了

这个问题我们要解决很简单,两个方法:

1、换一下代码的输入顺序,先输入字符串,再输入整型数,但是治标不治本

2、在输入整型数之后加一句代码:s.nextLine() 将回车键吃掉 ,这样就不会有问题了,治本

这是修改过的代码段,可以实现先输入整型数,紧接着再输入字符串的问题

import java.util.*;
public class Circle
{
	double radius;
	String color;
	public static void main(String[] args){
		Scanner s = new Scanner(System.in);
		System.out.print("请输入半径:");
		double r = s.nextDouble();
		s.nextLine();
		System.out.print("请输入圆的颜色:");
		String n = s.nextLine();
		Circle c = new Circle(r , n);
		System.out.println("圆形的颜色为:" + c.color);
		System.out.println("圆形的面积为:" + area(r) + " " + "," + " " + "圆形的周长为:" + perimeter(r));

	}
	public Circle(){
	}
	public Circle(double i , String c){
		radius = i;
		color = c;
	}
	public static double area(double n){
		return 3.14 * n * n;
	}
	public static double perimeter(double n){
		return 3.14 * 2 * n;
	}
}

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值