Explore BrainMass
Share

Explore BrainMass

    Java Static Methods and Counting Numbers of Objects

    This content was COPIED from BrainMass.com - View the original, and get the already-completed solution here!

    public class Syntax2
    {
    private int x, n;

    public Syntax2(int a, int b)
    {
    x = a;
    n = b;
    }

    public int sumofsquares(int x, int y)
    {
    return x * x + y * y;
    }

    public int nTimesProduct(int x, int y)
    {
    return n * x * y;
    }

    //test program
    public static void main(String[] args)
    {
    Keyboard kbd = new Keyboard();
    System.out.println("Enter two numbers ");
    int m = kbd.readInt();
    int n = kbd.readInt();
    System.out.println("The result is: " + sumofsquares(m, n));
    System.out.println("The other result is: " + nTimesProduct(m, n));
    }

    }

    The above code has the following two errors:

    Syntax2.java:39: non-static method sumofsquares(int,int) cannot be referenced from a static context: System.out.println("The result is: " + sumofsquares(m, n));
    Syntax2.java:40: non-static method nTimesProduct(int,int) cannot be referenced from a static context: System.out.println("The other result is:" + nTimesProduct(m, n));

    How do you rewrite this code so that it compiles and runs correctly, without making the sumofsquares and nTimesProduct methods static.

    -----------------------------

    Assume you have a class called Employee whose constructor takes two arguments: the employee's name and id number. Consider the following code fragment:

    Employee [ ] ea = new Employee[20];
    Employee emp1 = new Employee("Bob Jones", 34532);
    Employee emp2 = emp1;
    ea[0] = emp1;
    ea[1] = emp2;

    How many Employee objects exist in the heap in the above code? _______

    What is the total number of all objects in the heap in the above code? _______

    © BrainMass Inc. brainmass.com October 10, 2019, 7:26 am ad1c9bdddf
    https://brainmass.com/computer-science/java/java-static-methods-counting-numbers-objects-581411

    Solution Preview

    public class Syntax2
    {
    private int x, n;

    public Syntax2(int a, int b)
    {
    x = a;
    n = b;
    }

    public int sumofsquares(int x, int y)
    {
    return x * x + y * y;
    }

    public int nTimesProduct(int x, int y)
    {
    return n * x * y;
    }

    //test program
    public static void main(String[] args)
    {
    Keyboard kbd = new Keyboard();
    System.out.println("Enter two numbers ");
    int m = kbd.readInt();
    int n = kbd.readInt();
    System.out.println("The result is: " + sumofsquares(m, n));
    System.out.println("The other result is: ...

    Solution Summary

    This solution uses java class static methods and how to count the number of objects on the heap

    $2.19