Python 官方文档:入门教程 => 点击学习
目录scanner.nextInt()等next()和scanner.nextIine()连用注意事项实操出现问题原因解决Scanner类: next() 与 nextLine()与
背景:需求是输入二维矩阵行列数和矩阵的内容。
我想要的效果是这样的,用两个int记录第一行输入行列数,剩下用string记录用户输入的二维矩阵内容。
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
while(scanner.hasNext()) {
int x = scanner.nextInt();
int y = scanner.nextInt();
if (x==0&&y==0) {
scanner.close();
break;
}
//scanner.nextLine();
String a = "";
for (int i = 0; i < x; i++) {
a +=scanner.nextLine();
}
for (int i = 0; i < a.length(); i++) {
if (i%y == 0) {
System.out.println();
}
System.out.print(a.charAt(i));
}
}
}
输入却出现了问题,本想输入4行4列,却只接收了3行数据,就开始打印了
如图:
这就涉及到next()与nextline()方法区别的。
分隔符,它可能会缓冲所有输入信息,并查找要跳过的行。”
(假设还是以上输入)所以上面的代码分析是这样的:
在nextInt()与想接收数据nextline()之间再添加一行scanner.nextLine();用于缓冲换行符,换入新的一行。
int x = scanner.nextInt();
int y = scanner.nextInt();
if (x==0&&y==0) {
scanner.close();
break;
}
scanner.nextLine();//用于缓冲换行符,换入新的一行。
String a = "";
for (int i = 0; i < x; i++) {
a +=scanner.nextLine();
}
next()、nextLine()、nextInt()是scanner内置的方法。
1、一定要读取到有效字符后才可以结束输入。
2、对输入有效字符之前遇到的空白,next() 方法会自动将其去掉。
3、只有输入有效字符后才将其后面输入的空白作为分隔符或者结束符。
next() 不能得到带有空格的字符串。
Scanner scan = new Scanner(System.in);
System.out.print("请输入:");
String year = scan.next();
System.out.printf("%s",year);
输入:this is a test
输出:this
使用nextInt()方法时,与next()方法类似,只是它的返回值是int类型的,依旧将空格看作是两个输入的数据的间隔
(当使用nexInt()方法时,只能输入int类型的数据。)
1、以Enter为结束符,也就是说 nextLine()方法返回的是输入回车之前的所有字符。
2、可以获得空白。
Scanner scan = new Scanner(System.in);
System.out.print("请输入:");
String year = scan.nextln();
System.out.printf("%s",year);
输入:this is a test
输出:this is a test
用Scanner.useDelimiter( )方法,可以将分隔符号修改为"回车",或者其他字符。
//useDelimiter("\n"); //“\n”换行符(回车)作为输入的分隔符
Scanner scan = new Scanner(System.in).useDelimiter("\n");
System.out.print("请输入:");
String year = scan.next();
System.out.printf("%s",year);
输入:this is a test
输出:this is a test
注意:
使用nextLine()方法时,不将空格看做是两个字符串的间隔,而是看作字符串的一部分,返回时,它作为String类型一并返回
使用next()方法时,将空格看作是两个字符串的间隔
使用nextInt()方法时,与next()方法类似,只是它的返回值是int类型的,依旧将空格看作是两个输入的数据的间隔(当使用nexInt()方法时,只能输入int类型的数据。)
以上为个人经验,希望能给大家一个参考,也希望大家多多支持编程网。
--结束END--
本文标题: 关于scanner.nextInt()等next()和scanner.nextIine()连用注意事项
本文链接: https://www.lsjlt.com/news/202823.html(转载时请注明来源链接)
有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341
下载Word文档到电脑,方便收藏和打印~
2024-03-01
2024-03-01
2024-03-01
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
回答
回答
回答
回答
回答
回答
回答
回答
回答
回答
0