简体   繁体   中英

Name a New Instance in Java

I am trying to create a program that creates triangles by storing their sides in the class below:

class Triangle {
    private int[] sides;

    public Triangle(int x, int y, int z) {
        sides = new int[] {x,y,z};
        Arrays.sort(sides);
    }

    @Override public boolean equals(Object o) {
        return o instanceof Triangle && Arrays.equals(sides, ((Triangle) o).sides);
    }

    @Override public int hashCode() {
        return Arrays.hashCode(sides);
    }

    @Override public String toString() {
        return Arrays.toString(sides);
    }
}

The problem is that I do not know how to create a new instance of these triangles from a for loop. For example, I am comparing the GCD of three numbers via a for loop, and I then want to add a new triangle to a set (discussed here ). I believe I know how to everything but create a new instance of the class because, during the loop, there is no way for me to create unique instances of the triangle class.

Is there any way to do this?

Try this:

Set<Triangle> myTriangles = new LinkedHashSet<Triangle>();
for (something here) {
    myTriangles.add(new Triangle(a, b, c));
}

The Set will automatically avoid duplicates.

I think you made a little mistake in the way you initialize the object in the constructor. Well more than a mistake, i would say design problem.

Every triangle has 3 sides, so why dont you just say:

public Triangle(int x, int y, int z) {
        sides = new int[3];

        sides[0] = x;
        sides[1] = y;
        sides[2] = z;  
    }

Then when you create an object of class Triangle, you just pass the parameters to it. If you want to do it in a loop you could do something like this:

public static void main(String [] args) {

     Scanner sc = new Scanner(System.in);
      System.out.print("How many triangles do you want?") 
     int noOfTriangles = sc.nextInt();

     Triangle[] triangles = new Triangle[noOfTriangles];

     for(int i = 0; i < triangles.length; i++) {
          System.out.print("Creating triangle " + (i+1))
          System.out.print("Enter a value for side X")
          int x =sc.nextInt();
          System.out.print("Enter a value for side Y")
          int y =sc.nextInt();
                    System.out.print("Enter a value for side Z")
          int z =sc.nextInt();

            triangles[i] = new Triangle(x,y,z); 
     }

}

There you go now you have an Array of triangles with all objects initialized and values set.

I read the other post and added a running code of my own . perhaps you should look there. It generates the Triangles and everything. Anyway, this is not a "naming convention" question and would probably get the right feedback if you changed the question to "how to make an instance in java".

The complete code I wrote there (if you don't feel like clicking links) is here as well and should fill in any blanks other people left for you to fill in :

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
public class Triangle
{
    private int[]sides;
    public Triangle( int x, int y, int z)
    {
        sides = new int[]{x,y,z};
        Arrays.sort( sides );
    }

    public Triangle( String ... args )
    {
        this( Integer.parseInt( args[0].trim() ), Integer.parseInt( args[1].trim() ), Integer.parseInt( args[2].trim() ));
    }

    @Override
    public boolean equals( Object o )
    {
        if ( this == o ) return true;
        if ( o == null || getClass() != o.getClass() ) return false;

        Triangle triangle = ( Triangle ) o;

        if ( !Arrays.equals( sides, triangle.sides ) ) return false;

        return true;
    }

    @Override
    public int hashCode()
    {
        return sides != null ? Arrays.hashCode( sides ) : 0;
    }

    @Override
    public String toString()
    {
        return "Triangle{" +
                       "sides=" + Arrays.toString( sides ) +
                       '}';
    }

    public static void main( String[] args ) throws IOException
    {

        String[] input = new String[]{ "1,2,1" , "1,1,2", "1,2,3","1,3,1","1,1,1","1,3,3","1,1,3"};

        Set<Triangle> triangles = new HashSet<Triangle>(  );
        for ( String s : input )
        {
            triangles.add( new Triangle( s.split( "," ) ) );
        }
        System.out.println( "triangles = " + triangles );
    }
}

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