haverdaden haverdaden - 2 months ago 9
Java Question

How to check if an array contains elements?

I'm new to Java.

I have an array that looks like this (Array). (I've used Array.toString to print this). This is how the array is made: arraymade.
And this is read and made from a file in this format:

Nilsson;Lars;u;g;vg;vg
Svensson;Lena;vg;g;g;vg
Jonsson;Jonas;g;g;vg;g


I'm trying to make a method that returns either "u", "vg" or "g" depending on what the objects array contains.

@Override
public String getKursbetyg() {



if (Arrays.asList(uppgiftsbetyg).contains("u")) {
kursbetyg = "u";
return kursbetyg;

} else if (Arrays.asList(uppgiftsbetyg).contains("if the array contains 2 vg strings")) {
kursbetyg = "vg";
return kursbetyg;

} else {
kursbetyg = "g";
return kursbetyg;
}

}


This is the code I have now but it doesn't seem to work as it only returns "g" even though the array contains "u".

Also as you can see I want the method to only return vg when 2 vg:s are found because you need 2 vg:s to get the grade vg. So how do I check for double elements here ?

Answer

I'd say that you definitly should print you list made with Arrays.asList() in a for loop. Anyways, to check for double entries, you can do something like this:

if (Arrays.asList(uppgiftsbetyg).contains("vg")) {
        List temp = Arrays.asList(uppgiftsbetyg);
        temp.remove("vg");
            if(temp.contains("vg"){
            kursbetyg = "vg";
            return kursbetyg;
        }

    } 

Ever since List.remove() only removes the first object that equals the one specified, it wont remove the second "vg". Then you check if theres still a "vg", and you'll know if there's a second one.

Comments