简体   繁体   中英

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;
 }
}

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.

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.

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));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM