简体   繁体   中英

Not able to print a string using scanner

Here the input for string is " hi how are you" but I am getting output as "hi" alone. Do let me know where is the error. I have tried out with nextLine() also.

import java.util.Scanner;


public class Stringintalter {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Scanner sc=new Scanner(System.in);
        System.out.println("enter the num");
        int a = sc.nextInt();
        System.out.println("Enter the Double");
        double b = sc.nextDouble();
        System.out.println("Enter the string");
        String c = sc.next();  //tried out with nextLine() also.

        System.out.println(c);
        System.out.println(b);
        System.out.println(a);
    }

}

This is basic error only. I browsed a lot still I am not able to sort out the error.

everytime you do

    int a = sc.nextInt();

    double b = sc.nextDouble();

your scanner is not reading the newLine token, so you should do something like:

     System.out.println("enter the num");
    int a = sc.nextInt();
    sc.next();
    System.out.println("Enter the Double");
    double b = sc.nextDouble();
    sc.next();
    System.out.println("Enter the string");
    String c = sc.next();  //tried out with nextLine() also.

This code worked out for me.

import java.util.Scanner;


public class Stringintalter {

     public static void main(String[] args) {

         Scanner sc=new Scanner(System.in);
         System.out.println("enter the num");
         int a = sc.nextInt();
         System.out.println("Enter the Double");
         double b = sc.nextDouble();
         System.out.println("Enter the string");
         sc.nextLine();
         String c = sc.nextLine();
         System.out.println(c);
         System.out.println(b);
         System.out.println(a);
    }

}

Maybe this code will help you.

Scanner u = new Scanner(System.in);

     Scanner sc=new Scanner(System.in);
    System.out.println("enter the num");
    int a = sc.nextInt();
    System.out.println("Enter the Double");
    double b = sc.nextDouble();

    System.out.println(b);
    System.out.println(a);


    String c;
    c = u.nextLine();
    System.out.println(c);

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