Search code examples
javahashgethashset

How to retrive itrms froma set (hashset)


Good afternoon.

I am stuck in helping my son in a Java program. Hope someone can help. Here is the problem.

In Main i have, amoung other.... the read from scanner like this:

Scanner in = new Scanner(System.in);
    Chord c1 = createChord(in); // este chama o private static Chord createChord(Scanner in)
    Chord c2 = createChord(in);
    Chord c3 = createChord(in);
    Chord c4 = createChord(in);
    
    executeCommand(in);
    executeCommand(in);
    executeCommand(in);
    executeCommand(in);
    
    in.close();
            
}

    
    private static Chord createChord(Scanner in) {
    int n1 = in.nextInt();
    int n2 = in.nextInt();
    int n3 = in.nextInt(); 
    in.nextLine();
    //System.out.print(n1);
    //System.out.print(n2);
    //System.out.print(n3);
    return new Chord (n1, n2, n3);
    
    }

Lets assume the method returns values 1,2 and 3 into the hash Chord.

The question is How can i, in the program, retrieve the vaules from c1 to c4, for instance, the first or the third element from one of them?

I would greatly appreciate anny help.

Peter Rodrigues


Solution

  • If I understand you correctly your question is how to get the values you passed into Chord?

    You passed those values via the constructor and than you can save them as members in the object of the class. Those members can be made accessible via "Getters".

    Example:

    public class Chord {
    
        final int a;
        final int b;
        final int c;
    
        public Chord(final int a, final int b, final int c) {
            this.a = a;
            this.b = b;
            this.c = c;
        }
    
        public int getA() { return a; }
    
        public int getB() { return b; }
    
        public int getC() { return c; }
    
    }
    

    You can read up on that e.g. here.