gcp Logo

Let's get started with a program that uses variables and methods!

  • Login to your Repl.It account.
  • Click on: Languages
  • In the Popular section choose: Java: A concurrent, class-based, statically typed object-oriented language.
  • Click the pencil icon next to your repl name.
  • In the Default name: input box type: Variables_Functions
  • Delete all the lines of code provided as an example.
  • Copy the Triangle.java Template (Java) code (below)
  • Paste that code into your new Triangle class in the editor
  • Change the @author put-your-username-here
  • Replace the blank on the
        private int
        line with:
        S1, S2, S3
  • After the
        public Triangle ( int s1, int s2, int s3 ) {
    comment line add:
        S1=s1;
      S2=s2;
      S3=s3;
  • Replace the blank after the
        public int calculatePerimeter( ) {
    line with:
        return (S1+S2+S3)
  • Replace the blank on the
        Main t = new
        line with:
        Main(s1, s2, s3)
  • Click the Run icon
  • Triangle.java Template (Java)

    /**
     *
     * File: Triangle.java
     *
     * Create a Java class named Triangle that represents a "triangle" 
     * with the following characteristics:
     * 
     * 1) The class has three private integer instance variables 
     *    (S1, S2, S3) to store the sides of the triangle.
     * 2) This class has two constructors:
     *    Constructor #1 - has no parameters and initializes the 
     *    triangle's sides to 0
     *    Constructor #2 - has three integer parameters that 
     *    initializes the triangle's sides
     * 3) This class has a method calculatePerimeter( ) which 
     *    returns the perimeter (s1+s2+s3) of the triangle as an 
     *    integer
     * 4) This class contains a main( ) method which creates an 
     *    instance of the triangle object with 
     *    S1=10, S2=5, S3=2 and computes the object's perimeter 
     *    (via calculatePerimeter) and outputs the result to the 
     *    user's screen.
     *
     *
    /**
     *
     * @author put-your-name-here
     *
     */
    
    public class Main {
      public static int ___________________;
      public Main ( ) {
      }
    
      public Main (int s1, int s2, int s3) {
        ___________________
      }
    
      public int calculatePerimeter( ) {
        ___________________;
      }
    
      public static void main( String args[] ) {
      int s1 = 10;
      int s2 = 5;
      int s3 = 2;
        Main t = new __________________;
        System.out.println("The perimeter of a triangle with these sides (" + S1 + ", " + S2 + ", and "+ S3 + ") is: " + t.calculatePerimeter() );
      }
    }

    Triangle Class Output

    The perimeter of triangle with these sides () is: 17