13 Replies - 1102 Views - Last Post: 16 May 2014 - 02:01 PM Rate Topic: -----

#1 alfonsP  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 19
  • Joined: 05-May 14

I need help with methods involving loops

Posted 14 May 2014 - 06:43 PM

So I want the method getDisplayText of d to be returned as long as the for loop runs. When I do this I get a compile time error to enter a return statement. I am currently trying to fix it by returning an empty string, yet this doesn't seem the right way to go. Could someone please explain how to fix this?

public static String displayMultiple(Displayable d, int count)
    {
        for(int i = 1; i <= count; i++)
            return d.getDisplayText();
        return "";
    }



Is This A Good Question/Topic? 0
  • +

Replies To: I need help with methods involving loops

#2 PreDominance  Icon User is offline

  • New D.I.C Head

Reputation: 5
  • View blog
  • Posts: 14
  • Joined: 14-May 14

Re: I need help with methods involving loops

Posted 14 May 2014 - 06:52 PM

public static String[] displayMultiple(Displayable d, int count)
    {
        String[] arr = new String[count];
        for(int i = 0; i < count; i++)
            arr[i] = d.getDisplayText();
        return arr;
    }


You're trying to return multiple Strings when your function only wants to return one. Consider an array.

This post has been edited by Flukeshot: 14 May 2014 - 06:55 PM
Reason for edit:: edited on behalf of poster

Was This Post Helpful? 2
  • +
  • -

#3 Flukeshot  Icon User is offline

  • A little too OCD
  • member icon

Reputation: 416
  • View blog
  • Posts: 1,030
  • Joined: 14-November 12

Re: I need help with methods involving loops

Posted 14 May 2014 - 06:52 PM

You've got it inside out :) A method can only return once. What you need to do is perhaps have a collection of displayables and call displayText() on them.

Displayable[] collection = generateDisplayables(); // let's assume this creates an array of 20 displayables
for(int i = 0; i < collection.length; i++) { // loop until end of collection
   collection[i].getDisplayText();
}

Was This Post Helpful? 2
  • +
  • -

#4 PreDominance  Icon User is offline

  • New D.I.C Head

Reputation: 5
  • View blog
  • Posts: 14
  • Joined: 14-May 14

Re: I need help with methods involving loops

Posted 14 May 2014 - 06:53 PM

I can't fix my post -- but you'll need to start the array at 0, and go until (count-1).
Was This Post Helpful? 1
  • +
  • -

#5 jon.kiparsky  Icon User is online

  • Pancakes!
  • member icon


Reputation: 7807
  • View blog
  • Posts: 13,203
  • Joined: 19-March 11

Re: I need help with methods involving loops

Posted 14 May 2014 - 06:55 PM

If you declare a return type, the compiler insists that all branches lead to a return of that type. In this case, it is possible that count might be less than one, in which case the for loop would not execute. Therefore the compiler correctly sees that not all branches lead to a return, and complains. When you add a non-conditional return, the compiler is satisfied.

And in this case, if you're sure that an empty String is what you want to do when count <=0, this is a perfectly fine way to get that result. Some people might treat this as a user booboo and throw an exception, others might return a null. I think the best practice here would be to throw an exception, but "best practice" assumes a lot about the conditions, and those assumptions may not hold.


But let's look at your logic a little more closely.

Quote

So I want the method getDisplayText of d to be returned as long as the for loop runs.


A method returns exactly once. What is it that you want to get out of this? The same text repeated count times? Or what?
Was This Post Helpful? 2
  • +
  • -

#6 alfonsP  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 19
  • Joined: 05-May 14

Re: I need help with methods involving loops

Posted 14 May 2014 - 07:09 PM

View PostPreDominance, on 14 May 2014 - 06:52 PM, said:

public static String[] displayMultiple(Displayable d, int count)
    {
        String[] arr = new String[count];
        for(int i = 0; i < count; i++)
            arr[i] = d.getDisplayText();
        return arr;
    }


You're trying to return multiple Strings when your function only wants to return one. Consider an array.


I tried using this and got an ArrayIndexOutOfBounds Exception, so could you please explain why? Here is my code.

public class DisplayableTestApp
{
    public static void main(String args[])
    {
        System.out.println("Welcome to the Displayable Test application\n");

        // create an Employee object
        Displayable employee = new Employee(Employee.MARKETING, "Pineda-Knauseder", "Alfons", 34834.43);

        // display the employee information
        System.out.println(displayMultiple(employee, 2));

        // create a Product object
        Displayable product = new Product("java", "A java book", 49.99);
        
        // display the product information
        System.out.println(product.getDisplayText());
    }
    
    public static String[] displayMultiple(Displayable d, int count)
    {
        String[] collection = new String[count];
        for(int i = 1; i <= count; i++)
            collection[i] = d.getDisplayText();
        return collection;
    }
}


Also, I am following an exercise from my book. I am suppose to have this accomplished, yet it teaches me about arrays in the following chapters. Is there another possible way to accomplish the task of printing instance variables for objects depending on the count argument that is entered when the method is called?

View Postjon.kiparsky, on 14 May 2014 - 06:55 PM, said:

If you declare a return type, the compiler insists that all branches lead to a return of that type. In this case, it is possible that count might be less than one, in which case the for loop would not execute. Therefore the compiler correctly sees that not all branches lead to a return, and complains. When you add a non-conditional return, the compiler is satisfied.

And in this case, if you're sure that an empty String is what you want to do when count <=0, this is a perfectly fine way to get that result. Some people might treat this as a user booboo and throw an exception, others might return a null. I think the best practice here would be to throw an exception, but "best practice" assumes a lot about the conditions, and those assumptions may not hold.


But let's look at your logic a little more closely.

Quote

So I want the method getDisplayText of d to be returned as long as the for loop runs.


A method returns exactly once. What is it that you want to get out of this? The same text repeated count times? Or what?


Yes, that is exactly what I want. I would also like to accomplish this without using arrays.
Was This Post Helpful? 0
  • +
  • -

#7 jon.kiparsky  Icon User is online

  • Pancakes!
  • member icon


Reputation: 7807
  • View blog
  • Posts: 13,203
  • Joined: 19-March 11

Re: I need help with methods involving loops

Posted 14 May 2014 - 07:12 PM

I would think something like this would suffice...

for (int i = 0; i < count; i++) {
  System.out.println(d.getDisplayText());
  }


Was This Post Helpful? 0
  • +
  • -

#8 PreDominance  Icon User is offline

  • New D.I.C Head

Reputation: 5
  • View blog
  • Posts: 14
  • Joined: 14-May 14

Re: I need help with methods involving loops

Posted 14 May 2014 - 07:13 PM

You need to do count - 1, not count. If I have 15 objects in an array, and I try to get the 15'th element, you're gonna get an out of bounds.
Was This Post Helpful? 1
  • +
  • -

#9 jon.kiparsky  Icon User is online

  • Pancakes!
  • member icon


Reputation: 7807
  • View blog
  • Posts: 13,203
  • Joined: 19-March 11

Re: I need help with methods involving loops

Posted 14 May 2014 - 07:14 PM

for(int i = 1; i <= count; i++)




This is incorrect. Arrays in java are indexed from zero to length-1, not from 1 to length.
Was This Post Helpful? 1
  • +
  • -

#10 alfonsP  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 19
  • Joined: 05-May 14

Re: I need help with methods involving loops

Posted 14 May 2014 - 07:31 PM

View Postjon.kiparsky, on 14 May 2014 - 07:14 PM, said:

for(int i = 1; i <= count; i++)




This is incorrect. Arrays in java are indexed from zero to length-1, not from 1 to length.

I managed to get this working, yet this isn't really what I want. My book has not taught me about arrays yet, so therefore I am suppose to allow this method to return a string depending on the count argument. I am then to print it, so if I want to get information about an employee object and want it to print twice i enter 2 at the count argument. How would I do this?

Also, to make this clearer I am going to type the exercise from my book.

private static String displayMultiple(Displayable d, int count)

1. Write the code for this method so it returns a string that contains the Displayable parameter the number of times specified by the int parameter.
2. Modify the code in the main method so it uses the displayMultiple method to display the employee information once and the product information twice.

Am I reading this incorrectly or what?
Was This Post Helpful? 0
  • +
  • -

#11 jon.kiparsky  Icon User is online

  • Pancakes!
  • member icon


Reputation: 7807
  • View blog
  • Posts: 13,203
  • Joined: 19-March 11

Re: I need help with methods involving loops

Posted 14 May 2014 - 07:31 PM

You could concatenate the value onto itself in the loop, and then return the result. Take a look at "string concatenation" in your book. It's going to look almost exactly like what I did above, only this time you're going to assemble a String and return that String, so the loop will happen in the method.



EDIT: I think you're reading it correctly.

This post has been edited by jon.kiparsky: 14 May 2014 - 07:32 PM

Was This Post Helpful? 1
  • +
  • -

#12 alfonsP  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 19
  • Joined: 05-May 14

Re: I need help with methods involving loops

Posted 15 May 2014 - 02:36 PM

View Postjon.kiparsky, on 14 May 2014 - 07:31 PM, said:

You could concatenate the value onto itself in the loop, and then return the result. Take a look at "string concatenation" in your book. It's going to look almost exactly like what I did above, only this time you're going to assemble a String and return that String, so the loop will happen in the method.



EDIT: I think you're reading it correctly.

Thanks for the idea, and I just tried this. It's not working correctly; here's the code.
import java.util.Arrays;

public class DisplayableTestApp
{
    public static void main(String args[])
    {
        System.out.println("Welcome to the Displayable Test application");

        // create an Employee object
        Displayable employee = new Employee(Employee.MARKETING, "Pineda-Knauseder", "Alfons", 34834.43);
        System.out.println(displayMultiple(employee, 2));

        // display the employee information
        

        // create a Product object
        Displayable product = new Product("java", "A java book", 49.99);
        
        // display the product information
        
    }
    
    public static String displayMultiple(Displayable d, int count)
    {
        String information = "";
        for(int i = 1; i <= count; i++)
            information.concat(d.getDisplayText());
        return information;
    }
}


Output:
ant -f C:\\Users\\alfonso\\Downloads\\javp_allfiles\\java\\netbeans\\ex_starts\\ch09_ex1_DisplayableTest -Dnb.internal.action.name=run run
init:
Deleting: C:\Users\alfonso\Downloads\javp_allfiles\java\netbeans\ex_starts\ch09_ex1_DisplayableTest\build\built-jar.properties
deps-jar:
Updating property file: C:\Users\alfonso\Downloads\javp_allfiles\java\netbeans\ex_starts\ch09_ex1_DisplayableTest\build\built-jar.properties
compile:
run:
Welcome to the Displayable Test application

BUILD SUCCESSFUL (total time: 0 seconds)



I believe that the string, information, is just being printed as an empty string. It is not receiving the string that is returned by getDisplay() method. Why is this?

EDIT: My bad everybody; I was just discarding the value returned by the concat method by mistake. Anyways, here is the code just for future reference.
public static String displayMultiple(Displayable d, int count)
    {
        String information = "";
        for(int i = 1; i <= count; i++)
            information = information.concat(d.getDisplayText()).concat("\n");
        return information;
    }

Was This Post Helpful? 0
  • +
  • -

#13 Flukeshot  Icon User is offline

  • A little too OCD
  • member icon

Reputation: 416
  • View blog
  • Posts: 1,030
  • Joined: 14-November 12

Re: I need help with methods involving loops

Posted 15 May 2014 - 03:17 PM

Well, if you think about it, within that loop the variable 'd' will remain referenced to one object. This will simply repeat the one display text n times. Is that what you wanted?
Otherwise you would need a Collection or array of them passed into the method.
Was This Post Helpful? 0
  • +
  • -

#14 alfonsP  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 19
  • Joined: 05-May 14

Re: I need help with methods involving loops

Posted 16 May 2014 - 02:01 PM

View PostFlukeshot, on 15 May 2014 - 03:17 PM, said:

Well, if you think about it, within that loop the variable 'd' will remain referenced to one object. This will simply repeat the one display text n times. Is that what you wanted?
Otherwise you would need a Collection or array of them passed into the method.

Thank you for the information, but what I did is actually what I wanted.
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1