Thursday 4 January 2018

java - Issues with nextLine();













I
am trying create a program where it lets the user inputs values into an array using
scanner.



However, when the program asks for the
student's next of kin, it doesn't let the user to input anything and straight away ends
the program.



Below is the code that I have
done:



if(index!=-1)

{

Function.print("Enter full name: ");
stdName =
input.nextLine();

Function.print("Enter student no.:
");
stdNo = input.nextLine();

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


Function.print("Enter next of kin: ");

stdKin =
input.nextLine();

Student newStd = new Student(stdName, stdNo,
stdAge, stdKin);
stdDetails[index] = newStd;

}


I have tried using
next(); but it will only just take the first word of the user input which is not what I
wanted. Is there anyway to solve this problem?


class="post-text" itemprop="text">
class="normal">Answer



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

No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...