i have this dataset:

String[][] trainData= {
           //featIdx////////classInfo
            {"s", "y", "r"},//0
            {"s", "n", "r"},//1
            {"w", "y", "r"},//0
            {"r", "y", "p"},//0
            {"r", "n", "r"},//2
            {"r", "y", "p"},//0
            {"w", "n", "p"},//0
            {"w", "n", "r"},//3
            {"w", "y", "r"},//0
            {"s", "n", "r"}};//1
int[] trainClassInfo = {0, 1, 0, 0, 2, 0, 0, 3, 0, 1};

i want to check if the elements of trainClassInfo is all same at the indexes when trainData[0]=="s"
i wrote this method but it doesnt perform correctly, i'm confused ... :confused:

public boolean allSame(int featIdx, String featVal)
    {
        boolean allSame = false;
        int classInfo =-1;

            for(int i=0; i<trainData.length; i++){
                if(trainData[i][featIdx]==featVal){//when trainData element equals "s"
                    classInfo = trainClassInfo[i];//save classInfo temporarily
                }
            }

            for(int i=0; i<trainData.length; i++){
                if(trainData[i][featIdx]==featVal && trainClassInfo[i]==classInfo )
                    allSame = true;
                else 
                    allSame = false;
            }

        return allSame;
    }

it must return FALSE when i put this method like this: allSame(0, "s") , but it returns TRUE

Recommended Answers

All 5 Replies

to check for the equality of objects, you don't use the '==' operator, but you use the .equals method.

commented: good one +2

As stultuske pointed out you use equals that you either have to write or you can reuse something that already exists. For example Arrays.equals(Object[] a, Object[] a2)

I suspect the OP problem is much simpler; it is a purely logical error. Opon the first loop completion, classInfo is the value of the last qualifying trainClassInfo. The second loop always runs all the way through, and the last comparison always evaluates to True.
Solution: exit the second loop as soon as the mismatch is detected.

The OP should try debugging his code to see what is happening. If no interactive debugger available, add printlns to the code to show the execution flow and how the values of variables change.

i figured it out! thanks all :D

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.