2

I've been debugging the following program from hours yet I cannot find why is the sanner not taking the input for the field name

This is my source code:

import java.util.Scanner;

public class Student
{
int rollNo;
String name;
double percentageMarks;
static Scanner input = new Scanner(System.in);

public void accept()
{
    System.out.print("Enter roll no: ");
    rollNo = input.nextInt();

    System.out.print("Enter Name: ");
    name = input.nextLine();

    System.out.print("Enter percentageMarks: ");
    percentageMarks = input.nextDouble();
}

public void display()
{
    System.out.println("Name: " +name);
    System.out.println("roll no: " +rollNo);
    System.out.println("Percentage marks: " +percentageMarks);
}

public static void main(String[] args)
{
    Student s1 = new Student(), s2 = new Student();

    s1.accept();
    s2.accept();

    if(s1.percentageMarks>s2.percentageMarks)
        s1.display();
    else if (s2.percentageMarks>s1.percentageMarks)
        s2.display();
    else
        System.out.println("Both students has same marks");
}
}

This is an output sample:

Enter roll no: 1
Enter Name: Enter percentageMarks: 

As seen, without it allowing to enter student name, its prompting to enter student percentage marks.

Any suggestion please?

Bsquare ℬℬ
  • 4,241
  • 11
  • 21
  • 40
HQuser
  • 603
  • 10
  • 25
  • 2
    You can read this post I wrote to clarify your doubts about this problem: [Using `nextInt()` before `nextLine()`](https://christprogramming.wordpress.com/2014/01/30/java-common-mistakes-1/) – Christian Jan 19 '16 at 19:37
  • Probably the scanner taking the newline (from pressing Enter) as input and thus skipping to the next input line. – Bram Vanroy Jan 19 '16 at 19:59

1 Answers1

3

This is because you first have the input.nextInt() and after it is finished it is not going to the next line. Just parse the whole first line as Integer.parseInt(scanner.nextLine()) and you will get your input for the name after that.

tdrury
  • 2,189
  • 1
  • 19
  • 24
Simeon Vanov
  • 361
  • 3
  • 12