深圳排名网站,网页制作分工明细,做自己的网站给人的启发,高端网站开发秦帝目录 一、空格截断问题#xff1a;二、next()、nextInt()、nextDouble()等nextXxx()与nextLine()连用、混用的问题#xff1a;问题描述#xff1a;代码演示问题问题原因#xff1a;解决办法#xff1a;示例代码#xff1a; 最后 Java中使用键盘录入#xff0c;尤其是通过… 目录 一、空格截断问题二、next()、nextInt()、nextDouble()等nextXxx()与nextLine()连用、混用的问题问题描述代码演示问题问题原因解决办法示例代码 最后 Java中使用键盘录入尤其是通过Scanner类有时会遇到几个常见问题以下是一些问题及其解决方法 一、空格截断问题
当使用Scanner的next()方法读取带有空格的字符串时输入会在遇到空格时被截断。解决这个问题应该使用nextLine()方法来读取整行输入包括空格。
示例代码
Scanner scanner new Scanner(System.in);
String input scanner.nextLine(); // 使用nextLine读取整行输入二、next()、nextInt()、nextDouble()等nextXxx()与nextLine()连用、混用的问题
问题描述
键盘还未输入字符代码直接跳到下一个next方法略过了nextLine()方导致接收到的字符串为空。
代码演示问题 // 创建对象Scanner scanner new Scanner(System.in);// nextInt()System.out.println(输入数字);int i scanner.nextInt();System.out.println(scanner.nextInt:i);// nextLine()System.out.println(输入字符串);String s scanner.nextLine();System.out.println(scanner.nextLine:s);// nextDouble()System.out.println(输入数字);double d scanner.nextDouble();System.out.println(scanner.nextDouble:s);// nextLine()System.out.println(输入字符串);String s2 scanner.nextLine();System.out.println(scanner.nextLine:s2);// next()System.out.println(输入字符串);String s3 scanner.next();System.out.println(scanner.next:s3);// nextLine()String s4 scanner.nextLine();System.out.println(scanner.nextLine:s4);问题原因
如果在同一个Scanner实例中混用了nextXXX()方法如nextInt()、nextDouble()和nextLine()可能会遇到意料之外的行为。这是因为nextInt()等方法不会读取换行符导致后续的nextLine()直接读取之前留下的换行符。
解决办法
在使用完非nextLine()方法后添加一个额外的nextLine()来消费掉换行符。
示例代码
// 创建对象Scanner scanner new Scanner(System.in);// nextInt()System.out.println(输入数字);int i scanner.nextInt();System.out.println(scanner.nextInt:i);// 添加一个额外的nextLine()来消费掉换行符scanner.nextLine();// nextLine()System.out.println(输入字符串);String s scanner.nextLine();System.out.println(scanner.nextLine:s);// nextDouble()System.out.println(输入数字);double d scanner.nextDouble();System.out.println(scanner.nextDouble:s);// 添加一个额外的nextLine()来消费掉换行符scanner.nextLine();// nextLine()System.out.println(输入字符串);String s2 scanner.nextLine();System.out.println(scanner.nextLine:s2);// next()System.out.println(输入字符串);String s3 scanner.next();System.out.println(scanner.next:s3);// 添加一个额外的nextLine()来消费掉换行符scanner.nextLine();// nextLine()String s4 scanner.nextLine();System.out.println(scanner.nextLine:s4); 最后
如果感觉有收获的话点个赞 吧。 ❤️❤️❤️本人菜鸟修行期如有错误欢迎各位大佬评论批评指正
如果觉得这篇文对你有帮助的话也请给个点赞、收藏下吧非常感谢!