Issues with nextLine(); [duplicate]

纵饮孤独 提交于 2019-11-27 13:19:25

The problem occurs as you hit the enter key, which is a newline \n character. nextInt() consumes only the integer, but it skips the newline \n. To get around this problem, you may need to add an additional input.nextLine() after you read the int, which can consume the \n.

    Function.print("Enter age: ");
    stdAge = input.nextInt();
    input.nextLine();.

    // rest of the code

The problem is with the input.nextInt() this function only reads the int value. So when you continue reading with input.nextLine() you receive the "\n" Enter key. So to skip this you have to add the input.nextLine().

Function.print("Enter age: ");
stdAge = input.nextInt();
input.nextLine();
Function.print("Enter next of kin: ");
stdKin = input.nextLine();

Why next() is not working..?
next() returns next token , and nextLine() returns NextLine. It good if we know difference. A token is a string of non blank characters surrounded by white spaces.

From Doc

Finds and returns the next complete token from this scanner. A complete token is preceded and followed by input that matches the delimiter pattern. This method may block while waiting for input to scan, even if a previous invocation of hasNext() returned true.

Make input.nextLine(); call after input.nextInt(); which reads till end of line.

Example:

Function.print("Enter age: ");
stdAge = input.nextInt();
input.nextLine();  //Call nextLine

Function.print("Enter next of kin: ");
stdKin = input.nextLine();
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!