1

I have an issue reading the string,The scanner read the Integer and the double and it show's the output without reading the string.

I need your help.

public static void main(String[] args) {

    Scanner scan = new Scanner(System.in);
    int i = scan.nextInt();
    double d=scan.nextDouble();
    String s=scan.nextLine();

    scan.close();
    System.out.println("String: " + s);
    System.out.println("Double: " + d);
    System.out.println("Int: " + i);

}

}

zaynOm
  • 103
  • 1
  • 10

2 Answers2

1

Thankful to help. This error occurs because the nextInt() and nextDouble() methods don't read the newline characters of your input.

You can easily fix this either by parsing int from nextLine(): Integer.parseInt(scan.nextLine()) or simply using the InputStreamReader class as:

//sample code for understanding

InputStreamReader in=new InputStreamReader(System.in);
BufferedReader read=new BufferedReader(in);
//taking input
System.out.print("Enter a number: ");
int val=Integer.parseInt(read.readLine());
System.out.println("Value entered: "+val);
Jyotirmay
  • 513
  • 6
  • 22
0

The short of it? Don't call nextLine - it is confusing in how it operates.

If you want to read strings, use next() instead. If you want an entire line's worth, instead of a single word, update your scanner to work in 'line mode' instead of 'space mode':

Scanner scan = new Scanner(System.in);
scan.useDelimiter("\r?\n");

 // and now use as normal:

 int i = scan.nextInt();
 double d=scan.nextDouble();
 String s=scan.next();

That sets the scanner to scan up to newline characters, which are a little convoluted; on windows they are \r\n, but on other OSes they are just \n, hence why we specify: optional \r, then a required \n.

rzwitserloot
  • 85,357
  • 5
  • 51
  • 72