Java 扫描程序类无法获取字符串输入
这是一个简单的java代码。。但是Scanner类没有将字符串作为输入。为什么?Java 扫描程序类无法获取字符串输入,java,Java,这是一个简单的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("S
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);
}
使用
nextLine()。请参见此处的原因:因为sc.nextLine()
和sc.nextDouble()
方法不使用输入的换行符,因此在下次调用sc.nextLine()
使用字符串s=sc.next()代码>或添加sc.nextLine()代码>读取double
后。对字符串使用next()而不是nextLine(),但是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);
}