0

I ty to use arrays for storing student information. but when I run this code it's doesn't allow me to input student name. it jumpes from ID to sex by missing name. I don't know to fix this problem. Here is my code:

import java.util.Scanner;
// class student
class Student{
    private int ID;
    private String name;
    private String sex;
    private float score;
    Student(){}

    // function to input student information
    public void Input(){
        Scanner IN = new Scanner(System.in);
        System.out.print("Enter ID   : ");
        ID = IN.nextInt();
        System.out.print("Enter name : ");
        name = IN.nextLine();
        System.out.print("Enter sex  : ");
        sex = IN.nextLine();
        System.out.print("Enter score: ");
        score = IN.nextFloat();
    }

    // function to output student information
    public void Output(){
        System.out.println(ID + "\t" + name + "\t" + sex + "\t" + score + "\n");
    }
}
public class Main {
    public  static void IOStudent(){
        Scanner IN = new Scanner(System.in);
        int n;
        int i;
        System.out.print("Please enter number of student: ");
        n = IN.nextInt();
        System.out.println("Enter student information: ");
        Student []std = new Student[n];
        for(i = 0; i<n; i++){
            std[i] = new Student();
            std[i].Input();
        }
        System.out.println("All students information: ");
        for(i = 0; i<n; i++){
            std[i].Output();
        }
    }
    public static void main(String[] args) {
        IOStudent();
    }
}
  • `nextInt` does not consume the new line character left in the buffer, so the next call to `nextLine` consumes and skips to the next `nextLine` – MadProgrammer Nov 18 '20 at 04:03
  • Thank you for answer. So, how to fix it sir? – Thorn Sophean Nov 18 '20 at 04:15
  • You already have - use an extract `nextLine` after `nextInt` to consume the rouge new line. You could also read the line as a `String` and the parse the result as an `Integer` – MadProgrammer Nov 18 '20 at 04:28
  • Java naming conventions have class names start with a capital letter; methods and variables start with lower case letters. This makes it easier for experienced programmers to read and therefore help you. – NomadMaker Nov 18 '20 at 06:10

0 Answers0