java 输入理解

本文详细解析了Java中nextInt(), next() 和 nextLine() 方法的区别与应用场景。通过具体示例展示了如何正确使用这些方法来处理不同类型的输入数据。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

大家笔试面试中经常遇到输入和输出问题,一直懵懵懂懂,今天主要看下,给大家分享分享,顺便自己学习学习;

先解释一下next()、nextInt()、nextLine();

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

(只读int型值,nextInt()置光标于当前行所读值后)

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.

(读入输入直到空格出现。不能读取被空格符分隔的两个字符,next()置光标于当前行所读第一个值后

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.

看完之后nextInt()、next()和nextLine()的区别已经很清楚了,我觉得最容易出错的就是cursor问题。

(读入一行,包括用空格符分隔的字符串,nextLine()置光标于下一行开始处)

接下来举个例子详细说明:

第一种情况:

package com.Main.dl;
import java.util.Scanner;

public class Input {
    public static void main(String[] args){
        Scanner cin = new Scanner(System.in);
        int n = cin.nextInt();//第一行输入获取122
        String str = cin.nextLine();
        System.out.println("int型"+n+"string型"+str);
        System.out.println("END");
        }
}

输出结果:

122 33
int型122string型 33
END

解释:cin.nextInt()获得122值,光标移到122后面空格处,随后cin.nextLine()获取值,从光标处开始直到下一行开始处为33

如果要直接获得第二行输入,可以进行如下处理:

package com.Main.dl;

import java.util.Scanner;

public class MaxMap {
    public static void main(String[] args){
        Scanner cin = new Scanner(System.in);
        int n = cin.nextInt();
        String str1=cin.nextLine();
        String str = cin.nextLine();
        System.out.println("int型"+n+"中间的"+str1+"string型"+str);
        System.out.println("END");
        }
}

输入不同,输出不同;

第一种输出结果:

1
3
int型1中间的string型3
END

其中,  String str1=cin.nextLine();读取了第一行的\n移动光标到下一行初始位置,所以值为空字符串;

第二种输出结果:

1 2 
3
int型1中间的 2 string型3
END

其中,  String str1=cin.nextLine();读取了第一行的空格直到下一行初始位置,所以值为2,并且移动光标到下一行开始处;

 注意:

读取数字也可以使用nextLine(),不过需要转换:Integer.parseInt(cin.nextLine())。

注意在next()、nextInt()与nextLine()一起使用时,next()、nextInt()往往会读取部分数据(会留下"\n"或者空格之后的数据)。






评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值