Josh
Josh

Reputation: 31

Method Within a Method to replace a boolean statement

As part of a homework assignment I need to use this method:

public boolean validIndex(int index)
    {
        if ((index >= 0) && (index <= files.size() - 1)) {
            return true;
        }
        else {
            System.out.println("File not found.");
            return false;
        }
    }

and I need to implement it in this method instead of the boolean if statement:

public void listFile(int index)
    {
        if(index >= 0 && index < files.size()) {
            String filename = files.get(index);
            System.out.println(filename);
        }
    }

How do I call the original method in the second one?

Upvotes: 0

Views: 71

Answers (4)

candied_orange
candied_orange

Reputation: 7308

Be aware that:

public void listFile(int index)
{
    if(validIndex(index)) { 
        String filename = files.get(index);
        System.out.println(filename);
    }
}

is not going to behave exactly the same as:

public void listFile(int index)
{
    if(index >= 0 && index < files.size()) {
        String filename = files.get(index);
        System.out.println(filename);
    }
}

because:

public boolean validIndex(int index)
{
    if ((index >= 0) && (index <= files.size() - 1)) {
        return true;
    }
    else {
        System.out.println("File not found.");
        return false;
    }
}

has a key difference: the "File no found" line.

By the way,

((index >= 0) && (index <= files.size() - 1)) 

and

 (index >= 0  &&  index <  files.size())

turn out to be the same even though they look different.

Upvotes: 0

Thiyagu
Thiyagu

Reputation: 17880

Call validIndex inside if statement in listFile function

if(validIndex(index))
{
   String filename = files.get(index);
   System.out.println(filename);
}

So if the validIndex funtion returns True then this will be evaluated as if(True) and the body of the function will be executed.

If the validIndex returns False then this will be if(False) and the function body will not be executed.

Upvotes: 1

Tdorno
Tdorno

Reputation: 1571

This will return the boolean value from said validIndex method and that value will determine the control flow of the if that it is being called by.

if(validIndex(index))

Upvotes: 0

August
August

Reputation: 12558

It looks like you want something like this:

public void listFile(int index)
{
    if(validIndex(index)) { 
        String filename = files.get(index);
        System.out.println(filename);
    }
}

Upvotes: 0

Related Questions