gpt4 book ai didi

java - 为什么数组使用扫描仪在 java 中显示两个索引

转载 作者:行者123 更新时间:2023-11-29 05:33:19 24 4
gpt4 key购买 nike

import java.util.Scanner;

public class test{

public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.println("Enter maximum number : ");
int items = input.nextInt();
String arr[] = new String[items];
int x = 0;
while(x < items)
{

System.out.println("Enter item " + x + ":");
arr[x] = input.nextLine();
x++;
}
}
}

在我的代码中,首先是我询问数组索引中的最大数并存储到 arr[]。现在,当我按回车键时发现错误,它显示"Enter item 0""Enter item 1"。它显示索引 arr[1] 。应该显示的是“Enter item 0”仅在我第一次按下回车键。有人知道吗?

谢谢

最佳答案

问题是 nextInt()扫描仪方法不处理行尾 (EOL) 标记,因此当您调用 input.nextInt() 时它会悬空只在你打电话时被困住 input.nextLine() 确实处理 EOL token 。

一种解决方案是调用 nextLine()明确地处理悬空 token 并允许扫描器为您的下一个完整输入行做好准备:

int items = input.nextInt();
input.nextLine(); // add this

当您创建一行文本并按 <enter> 时, 额外的 1-2 个字符会附加到文本的末尾。一个常见的称为换行符或 LF,它在数字上表示为十进制 10,并由 \n 的字符表示。 ,另一个称为回车符或 CR,用数字表示为 13,按字符表示为 \r。 . Unix 和 Apple OS 系统通常只附加 LF,而 Windows/DOS 系统将 LF 和 CR 一起附加。

如果您调用 input.nextInt()在一行文本上,Scanner 将抓取 int 文本,但不会抓取行尾标记或上述字符,这些字符将悬空或未处理。如果您调用 input.nextInt()并且在下一行有更多的数字输入,然后扫描仪将跳过 EOL 标记并获取数字文本,但是如果您调用 input.nextLine()扫描器将获取 EOL 代币,除此之外别无他物。

关于java - 为什么数组使用扫描仪在 java 中显示两个索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20366352/

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