feelingstoned
feelingstoned

Reputation: 95

Incompatible types error in ArrayList but both are String

I'm fairly new to Java so don't attack me lol but I've created two classes and an ArrayList in one of them. I can't compile and get this error: "incompatible types: java.lang.String cannot be converted to int" but nothing is being converted here? First class:

import java.util.ArrayList;
public class TestScores {
 private ArrayList < Class > scores;
 public int studentScores;
 public TestScores() {
  scores = new ArrayList < Class > ();
 }
 public void add(String name, int score) {
  scores.add(new Class(name, score));
 }
}

Second Class:

public class Class {
 public int score;
 public String name;
 public Class(int aScore, String aName) {
  score = aScore;
  name = aName;
 }
}

Upvotes: 1

Views: 1196

Answers (3)

Guy
Guy

Reputation: 50809

public Class(int aScore, String aName) receives first parameter int and second String, but you send it vice versa.

In scores.add(new Class(name, score)); you send the String first and the int second. It should be

scores.add(new Class(score, name));

Upvotes: 0

Chris Kitching
Chris Kitching

Reputation: 2655

Firstly, don't call a class Class. There's a built-in class called Class: https://docs.oracle.com/javase/7/docs/api/java/lang/Class.html

While it's allowed, it's just unclear. Get into the habit of giving things descriptive names.

Your error is caused by the arguments being backwards. You construct a new Class like:

new Class(name, score)

But your constructor expects score first, then name:

public Class(int aScore, String aName)

Arguments in Java, unlike they sometimes are in Python, are matched by position not name. So you tried to bind the local String name to the int parameter aScore, hence the compile error.

Upvotes: 3

Renuka Deshmukh
Renuka Deshmukh

Reputation: 998

either change your constructor to

public Classname( String aName, int aScore,)
{
    score = aScore;
    name = aName;
}

your constructor accepts first integer and then string, but you are passing string first.

Upvotes: 0

Related Questions