Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inputting into an array using scanner class (error: incompatible types: Scanner cannot be converted to String)

I'm trying to input student details using a scanner but I keep getting this error:

error: incompatible types: Scanner cannot be converted to String

I have 4 scanners which are

static Scanner name = new Scanner(System.in);
static Scanner Date = new Scanner(System.in);
static Scanner address = new Scanner(System.in);
static Scanner gender = new Scanner(System.in);

My code is as follows

System.out.println("You have chosen to add a student. Please enter the following details");
System.out.println("Name: ");
String Name = name.nextLine();  
System.out.println("DOB: ");
String DOB = Date.nextLine();
System.out.println("Address: ");
String Address = address.nextLine();
System.out.println("Gender: ");
String Gender = gender.nextLine();

app.addStudent(name, DOB, address, gender);
System.out.println(Name + " has been added!" + "\n" + "Returning to menu....");

app.delay();

The addStudent method is as follows

public void addStudent (String name,String DOB,String address,String gender)
{
    for(int i = 0; i < enrolment.length; i++)
    {
        if (enrolment[i] == null)
        {
            this.enrolment[size] = new Student(name, DOB, address, gender);
            this.size++;

            if (gender == "Male")
            { 
                this.maleStudents++;
            }
            else { 
                this.femaleStudents++; 
            }
            break;
        }
    }
}
like image 542
user4808539 Avatar asked Mar 16 '23 09:03

user4808539


1 Answers

The problem is that you're passing your Scanner objects to your addStudent method instead of the strings that you obtained from the scanners:

app.addStudent(name, DOB, address, gender);

Should be

app.addStudent(Name, DOB, Address, Gender);

Also:

  • one Scanner object should be sufficient. No need for four of them.
  • Java code conventions dictate that variable names are in lower camel-case, i.e. gender instead of Gender.

Putting everything together, your code should look something like this:

Scanner scanner = new Scanner(System.in);

System.out.println("You have chosen to add a student. Please enter the following details");

System.out.println("Name: ");
String name = scanner.nextLine();

System.out.println("DOB: ");
String dob = scanner.nextLine();

System.out.println("Address: ");
String address = scanner.nextLine();

System.out.println("Gender: ");
String gender = scanner.nextLine();

app.addStudent(name, dob, address, gender);

System.out.println(name + " has been added!" + "\n" + "Returning to menu....");
like image 81
Robby Cornelissen Avatar answered Mar 30 '23 01:03

Robby Cornelissen