简体   繁体   中英

how to read space before string using scanner in java?

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);
}
}

input : (before 'ram' have 5 space)

343434343

343.434343

ram sdf

Expected output :(before 'ram' have 5 space)

ram sdf

343.434343

343434343

You don't have to create two scanners. Also, you'll need to do nextLine() once you read the double.

Here is the corrected code snippet:

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);
}

Output:

String:      ram sdf
Double: 343.434343
Int: 343

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM