Wednesday, 15 July 2015

Obtaining Value from a Method (java) -



Obtaining Value from a Method (java) -

i have gotten code work out far, trying larn how finish method compile total amount of sides used , print value on in lastly print line. problem method gettotalsides, have set homecoming 0, want homecoming total sides instead, meaning: mp1.getsides() + mp2.getsides() + mp3.getsides() + mp4.getsides().

public class testparts { public static void main(string[] args) { mypolygon mp1 = new mypolygon(); mypolygon mp2 = new mypolygon(4); mypolygon mp3 = new mypolygon(5); mypolygon mp4 = new mypolygon(6); system.out.println("polygon 1 has " + mp1.getsides() + " sides, angles total " + mp1.getsumofangles()); system.out.println("polygon 2 has " + mp2.getsides() + " sides, angles total " + mp2.getsumofangles()); system.out.println("polygon 3 has " + mp3.getsides() + " sides, angles total " + mp3.getsumofangles()); system.out.println("polygon 4 has " + mp4.getsides() + " sides, angles total " + mp4.getsumofangles()); system.out.println("there " + mypolygon.gettotalsides() + " total sides"); } } class mypolygon { double getsides; mypolygon() { getsides = 3; } static double gettotalsides() { homecoming 0; } double getsides() { // todo auto-generated method stub homecoming getsides; } mypolygon(double newgetsides) { getsides = newgetsides; } double getsumofangles() { homecoming ((getsides - 2) * 180); } void setgetsides(double newgetsides) { getsides = newgetsides; }

if need method, can utilize varargs (variable arity arguments) purpose:

static double gettotalsides(mypolygon... polygons) { double x = 0; (mypolygon p: polygons) { x+= p.getsides(); } homecoming x; }

then phone call this:

system.out.println("there " + mypolygon.gettotalsides(mp1,mp2,mp3,mp4) + " total sides");

or create array

mypolygon mypolygons = new mypolygon [4]; mypolygons [0] = mp1; mypolygons [1] = mp2; mypolygons [2] = mp3; mypolygons [3] = mp4; system.out.println("there " + mypolygon.gettotalsides(mypolygons) + " total sides");

however, improve solution store polygons in array/list beginning pass whole array/list them off method, loop, , homecoming result. aware though, lists , arrays different, , so, neeed modify method signature accordingly.

java methods

No comments:

Post a Comment