gpt4 book ai didi

java - 扫描仪类别 : Two inputs on the same line, 以空格分隔

转载 作者:行者123 更新时间:2023-12-02 09:42:59 24 4
gpt4 key购买 nike

在下面的代码中:

import java.util.Scanner;

class A
{
public static void main()
{
Scanner sc = new Scanner(System.in);
System.out.println("Enter the first number: ");
int a = sc.nextInt();
System.out.println("Enter the second number: ");
int b = sc.nextInt();

System.out.println(a);
System.out.println(b);
}
}

如果我在显示第一条消息后在一行中输入两个数字(以空格分隔),则这两个数字将同时作为输入,然后显示第二条消息。为什么会这样?

最佳答案

nextInt() 为您提供下一个输入,无论输入是否在同一行。

要仅获取每行的第一个值,您可以在对 sc.nextInt() 的调用之间使用 sc.nextLine() 来使用行终止符并移动到下一行:

System.out.println("Enter the first number: ");
int a=sc.nextInt();

sc.nextLine(); //Place this to ensure other inputs on same line don't matter

System.out.println("Enter the second number: ");
int b=sc.nextInt();

//Without the nextLine it will set c to the next int even on same line as b

System.out.println("Enter the third number: ");
int c=sc.nextInt();

System.out.println("a = " + a);
System.out.println("b = " + b);
System.out.println("c = " + c);

测试运行:

Enter the first number: 
1 2 3 4 5
Enter the second number:
78 89 99
Enter the third number:

输出:

a = 1
b = 78
c = 89

如您所见,扫描仪只会将a设置为1并忽略2 3 4 5,然后等待下一个输入对于下一行的 b 并将 b 设置为 78

但是,c 将被设置为 89,因为 扫描仪 没有被告知移至下一行,然后打印语句将在之后运行,没有输入任何内容的选项。

关于java - 扫描仪类别 : Two inputs on the same line, 以空格分隔,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56907975/

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