如何在java中使用scanner扫描字符串之前读取空格?

时间:2016-04-10 08:47:08

标签: java input java.util.scanner

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

1 个答案:

答案 0 :(得分:1)

您不必创建两个扫描仪。另外,一旦你阅读了双重文件,你就需要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