Jump to content

Java uzdevums


aiznemts

Recommended Posts

Sveiki,

 

 

Sāku nedaudz paprogrammēt iekš Java.

 

Dots šāds uzdevums:

 

Write the necessary classes to support the following main:
static public void main(String[] args) {
Expression e =
new Sum(
new PowerOf(
new Number(2.0), new Number(3.0)),
new Sum(
new Number(1.0), new Average(1,3)));
System.out.println(e + " = " + e.evaluate());
}
Average – vidējais
PowerOf  - pakāpē
Sum – summa
Number – atgriež skaitli

 

Cik sapratu tad izpildīju kā domāju, bet rāda kļūdas par neatbilstošiem tipiem.

 

Kur varētu būt kļūda?

 

public class Main {
   public static void main(String[] args) {
    Expression e =
		    new Sum(
				    new PowerOf(
						    new Number((float) 2.0), new Number((float) 3.0)),
				    new Sum(
						    new Number((float) 1.0), new Average(1, 3)));
    System.out.println(e + " = " + e.evaluate());
   }
   static class Sum {
    private float num1;
    private float num2;
    public Sum(float num1, float num2) {
	    float sum = num1 + num2;
	    //return sum;
    }
   }
   static class PowerOf {
    private float base;
    private float exp;
    public PowerOf(float base, float exp) {
	    float temp = (float) Math.pow(base, exp);
    }
   }
   public static class Number {
    private float num;
    public Number(float num) {
	    this.num = num;
    }
   }
   public static class Average {
    private float num1;
    private float num2;
    public Average(float num1, float num2) {
	    float avg = ((num1 + num2) / 2);
    }
   }
}

 

Paldies!

Link to post
Share on other sites

Kā redzams uzdevuma nosacījumos, tad, piemēram, klase Sum konstruktorā saņem divus parametrus, pie kam divos dažādos gadījumos dažādus, pirmajā PowerOf un Sum, otrajā Number un Average.

Tas nav tas pats, kas float, kā pats uzrakstīji.

Es šo uzdevumu risinātu definējot abstraktu bāzes klasi Expression ar abstraktu evalutate funkciju priekš visām Sum, Average, PowerOf, Number klasēm, kas katra prot saņemt konstrutoros vai nu tos floatus vai arī citas Expression klases, lai nav jāveido divi dažādi, kā Sum gadījumā.

Attiecīgi katrai klasei jāimplementē evaluate...

Un man apnika stāstīt... :)

http://en.wikipedia.org/wiki/Inheritance_(object-oriented_programming)

Link to post
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Loading...
×
×
  • Create New...