为何无法在以下Java代码中为字符串s1输入内容?
为啥字符串变量s1没法输入内容?
嘿,这个问题我初学Java时也踩过一模一样的坑!咱们来唠唠核心原因:
问题根源:Scanner方法的行为差异
当你用in.nextInt()和in.nextDouble()读取预算和时长时,这两个方法只会读取输入里的数值部分,完全不会处理你输入完数值后按下的换行符(就是键盘上的回车,对应字符\n)。这个换行符会留在输入流里“卡着”没被处理。
等到执行String s1 = in.nextLine();的时候,Scanner会直接读取输入流里剩下的这个换行符,把它当成一个空的输入行,所以s1直接被赋值成了空字符串,看起来就像程序跳过了s1的输入步骤。
两种实用解决办法
办法1:手动吃掉残留的换行符
在每次调用nextInt()/nextDouble()之后,额外加一行in.nextLine()来消耗掉留在输入流里的换行符:
import java.util.*; public class MovieInfo { public static void main(String[] args) { Scanner in = new Scanner(System.in); System.out.println("Enter the name of the film"); String name = in.nextLine(); System.out.println("Enter the film budget"); int bud = in.nextInt(); in.nextLine(); // 吃掉预算输入后的换行符 System.out.println("Enter the running time"); double time = in.nextDouble(); in.nextLine(); // 吃掉时长输入后的换行符 System.out.println("Enter the film production house"); String s1 = in.nextLine(); System.out.println("Film being screened : "+name); // 后续输出内容... } }
办法2:统一用nextLine()读取,再手动转换类型
这种方法更统一,所有输入都用nextLine()读取,然后把字符串转换成对应的数值类型:
import java.util.*; public class MovieInfo { public static void main(String[] args) { Scanner in = new Scanner(System.in); System.out.println("Enter the name of the film"); String name = in.nextLine(); System.out.println("Enter the film budget"); int bud = Integer.parseInt(in.nextLine()); // 字符串转int System.out.println("Enter the running time"); double time = Double.parseDouble(in.nextLine()); // 字符串转double System.out.println("Enter the film production house"); String s1 = in.nextLine(); System.out.println("Film being screened : "+name); // 后续输出内容... } }
这样就能正常给s1输入内容啦!
内容的提问来源于stack exchange,提问作者shreyas.k
相关产品推荐
相关产品推荐

