Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java program is not able to read a string

Tags:

java

import java.util.*;

class DataTypes {

    public static void main(String args[]) {
        int i = 4;
        double d= 4.0;
        String s = "Hackerrank";
        Scanner scan = new Scanner(System.in);
        int j = scan.nextInt();
        double d1 = scan.nextDouble();
        String s1 = new String();
        s1 = scan.nextLine();
        j = j+i;
        System.out.println(j);
        d1 = d1+d;
        System.out.println(d1);
        System.out.println(s+" "+s1);
        scan.close();
    }
}

See the above code it is error free but after I input the double the program does not read the string it directly shows the output. But When I comment the scanning statements of int and double then the programs reads my string. Why is it so?

like image 354
Andy.inamdar Avatar asked Sep 02 '25 16:09

Andy.inamdar


1 Answers

You are not reading the string as you want, just use below code to make it work as you want

s1 = scan.next();

For more information please see this link

EDIT :
If your input consist a string with spaces than you can do something like:

scan.nextLine();
s1 = scan.nextLine();

This is because of nextDouble(), this method does not consume the last newline character of your input, and thus that newline is consumed in the next call to nextLine(). Adding newLine() before reading String will consume the new Line and you will be able to input your String.

like image 173
Lalit Verma Avatar answered Sep 04 '25 05:09

Lalit Verma