gpt4 book ai didi

java - 扫描器类无法接受字符串输入

转载 作者:行者123 更新时间:2023-11-30 08:05:03 26 4
gpt4 key购买 nike

这是一个简单的 java 代码..但是 Scanner 类没有将字符串作为输入。为什么?

public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
int x=sc.nextInt();
double y=sc.nextDouble();
String s =sc.nextLine();

System.out.println("String: "+s);
System.out.println("Double: "+y);
System.out.println("Int: "+x);
}

最佳答案

因为sc.nextInt()sc.nextDouble()方法不会消耗你输入的换行符,所以换行符会在下次调用时被消耗到 sc.nextLine()

public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
int x=sc.nextInt();
sc.nextLine();
double y=sc.nextDouble();
sc.nextLine();
String s =sc.nextLine();

System.out.println("String: "+s);
System.out.println("Double: "+y);
System.out.println("Int: "+x);
}

关于java - 扫描器类无法接受字符串输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35252729/

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