gpt4 book ai didi

java - 如何使用java中的扫描器读取字符串之前的空格?

转载 作者:行者123 更新时间:2023-12-01 10:05:11 25 4
gpt4 key购买 nike

import java.util.Scanner;
import java.io.*;

public class Solution {

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

Double y= sc.nextDouble();
Scanner sc1=new Scanner(System.in);
String name = sc1.nextLine();


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

输入:(“ram”之前有5个空格)

343434343

343.434343

ram sdf

预期输出:(“ram”之前有 5 个空格)

ram sdf

343.434343

343434343

最佳答案

您不必创建两个扫描仪。另外,读取 double 后,您需要执行 nextLine()

这是更正后的代码片段:

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

/* Note the change here */
sc.nextLine();
String name = sc.nextLine();

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

输出:

String:      ram sdf
Double: 343.434343
Int: 343

关于java - 如何使用java中的扫描器读取字符串之前的空格?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36527708/

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