Scanner nextLine Java error

I want a program in java to accept

1.Integer

2.Double

3.String respectively . and display the above .

But the problem I m facing is after I enter integer and double its not prompting me to enter String . Its directly display the values . As i searched the soln to this , I got to know that

scan.nextLine(); 

should be used after I accept the double value .

can anyone tell me why should use this line . I read the doc of nextLine . But I didnt understand .

import java.util.Scanner;

public class Solution {

    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        int i = scan.nextInt();
        double d = scan.nextDouble();
        //   scan.nextLine();            **Why should I write this ??**
        String s = scan.nextLine();

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

According to nextLine() javadoc:

Advances this scanner past the current line and returns the input that was skipped. This method returns the rest of the current line, excluding any line separator at the end. The position is set to the beginning of the next line.

After input of double value, nextLine() reads the remainder on the line containing the double number. That's why you need another nextLine() for input string.

Using next() would solve your problem:

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

System.out.println("String: " + s);
System.out.println("Double: " + d);
System.out.println("Int: " + i);
链接地址: http://www.djcxy.com/p/96072.html

上一篇: 扫描仪读取下一行命令的麻烦

下一篇: 扫描仪nextLine Java错误