gpt4 book ai didi

java - 为什么 nextInt() 忽略/n?

转载 作者:行者123 更新时间:2023-11-30 02:46:09 25 4
gpt4 key购买 nike

我的代码遇到了问题,幸运的是我能够通过此处的另一个类似问题解决该问题,但我很好奇为什么会发生这种情况。

这是我的程序的简化版本:

public static void main(String[] args){
Scanner scan = new Scanner(System.in);
String input = scan.nextLine();

while(!input.equals("x")){

if(input.equals("m")){
String temp = scan.nextLine();
String entry = scan.nextLine();
}
else if(input.equals("f")){
String color = scan.nextLine();
int nothing = scan.nextInt();
}

System.out.println("Enter 'm' for mascara, 'f' for foundation, 'x' to exit");
System.out.println("Entry? :");
input = scan.nextLine();
}
}

使用这段代码,输入“m”不会给我带来任何问题,但“f”会让我将这两行打印两次。为什么 nextInt() 会发生这种情况,而 nextLine() 却不会?

'm'
Enter 'm' for mascara, 'f' for foundation, 'x' to exit
Entry? :
'f'
Enter 'm' for mascara, 'f' for foundation, 'x' to exit
Entry? :
Enter 'm' for mascara, 'f' for foundation, 'x' to exit
Entry? :

最佳答案

Why does nextInt() ignore \n?

它不会忽略它。它只是不读取它1

事实上,这里的异常方法是 nextLine 方法。大多数 next 方法都是通过获取下一个标记然后尝试解析标记来工作的。获取下一个 token 意味着:

  1. 跳过所有前导分隔符(默认为空格)
  2. 读取直至字符,但不包括下一个分隔符。

nextLine() 方法不同。它只是读取直到并包括下一个行尾序列的所有字符。

<小时/>

1 - ...除非它是调用 nextInt() 时的前导分隔符之一!

关于java - 为什么 nextInt() 忽略/n?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40145337/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com