-1

I'm using on program that I need get input from console in java. here is a simple code only for showing you the problem. public class Main {

public static void main(String args[])
{
    // Using Scanner for Getting Input from User
    Scanner in = new Scanner(System.in);

    String s = in.nextLine();
    System.out.println("You entered string "+s);

    int a = in.nextInt();
    System.out.println("You entered integer "+a);

    float b = in.nextFloat();
    System.out.println("You entered float "+b);
    System.out.println();

}

}

for input :

"stackOverFlow"
12
3.4

out put is : You entered string stackOverFlow You entered integer 12

and out put should be : You entered string stackOverFlow You entered integer 12 You entered float 3.4

what is the problem why the last line don't be read by scanner ?

RealSkeptic
  • 32,074
  • 7
  • 48
  • 75
Aybab
  • 1
  • 2
  • Looks like it's waiting for you to press enter after the 3.4. – RealSkeptic Mar 04 '20 at 12:23
  • Add `in.nextLine();` before `float b = in.nextFloat();` – Sudhir Ojha Mar 04 '20 at 12:26
  • I think there something happening when you try to read line and then integer. The reader consumes the input in different ways and there it might not work. Check to read only int or string. A solution is to read only lines and parse them to Integer – Jim_Ktr Mar 04 '20 at 12:27

1 Answers1

1

Scanner does not work like this. in.nextLine() will consume the whole line and wait for you to press return, and then call the next statement, which happens to be a print. Then, it expects you to enter an int, so on...

Your program would expect input as follows:

> stackOverFlow
You entered string stackOverFlow
> 12
You entered integer 12
> 3.4
You entered float 3.4

If you want to parse a String, int, and float from the first string a user enters, that is a different operation (assuming you enter some string that would be split into 3 elements by a space):

import java.util.Scanner;

public class Test {
    static int i;
    static float f;

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

        System.out.println("Enter a: string int float");

        String s = in.nextLine();
        String[] split = s.split(" ");

        String str = split[0];

        try {
            i = Integer.parseInt(split[1]);
        } catch (NumberFormatException e) {
            e.printStackTrace();
        }
        try {
            f = Float.parseFloat(split[2]);
        } catch (NumberFormatException e) {
            e.printStackTrace();
        }

        System.out.println("String: " + str);
        System.out.println("Int: " + i);
        System.out.println("Float: " + f);

        in.close();
    }
}
sleepToken
  • 1,804
  • 1
  • 12
  • 21