Codingbat - Java - Array1 - firstLast6 - How to Call the Boolean Method with an Array as a Parameter

Codingbat - Java - Array1 - firstLast6 - How to Call the Boolean Method with an Array as a Parameter

I hope all is well. I've recently solved an algorithm in Coding Bat (Java - Array1 - firstLast6):

Problem

*Given an array of ints, return true if 6 appears as either the first or last element in the array. The array will be length 1 or more.

firstLast6([1, 2, 6]) → true

firstLast6([6, 1, 2, 3]) → true

firstLast6([13, 6, 1, 2, 3]) → false*

My Solution

public boolean firstLast6(int[] nums) {
  
  if ( (nums[0] == 6) || (nums[nums.length - 1]) == 6 ) {
    
    return true;
    
  }
  
  return false;
  
}

This is the correct solution. However, it's one thing to solve the problem in Coding Bat, but I want to be able to call this boolean method in my VS Code editor in the main method. My research thus hasn't produced a solid answer to my question.

In the main method:

  1. Boolean method call: How would you call the boolean method that has an array (nums) as a parameter? I'm stuck on the syntax for this part.

  2. Print out statement: Using "System.out.println()" print out the true or false result?

VS Code - Full Layout

public class ReturnStatements {

    public static void main(String[] args) {

        // Method call
        
        // Print out statement outputing true or false.

    }
    
    public static boolean firstLast6(int[] nums) {

        if ( nums[0] == 6 || nums[nums.length - 1] == 6 ) {

            return true;

        }

        return false;
    }

}
5

2 Answers

You can do:

public static void main(String[] args) {
    System.out.println(fistLast6(new int[] {1, 2, 6}));
}

And @thinkgruen's suggestion:

public static boolean firstLast6(int[] nums) {
    return nums[0] == 6 || nums[nums.length - 1] == 6;
}
1
public class ReturnStatements {

    public static void main(String[] args) {

        // Method call
        boolean toFirstLast6 = firstLast6(new int[] {1, 2, 6});

        // Print out statement outputing true or false 
        System.out.println(toFirstLast6);

    }

    public static boolean firstLast6(int[] nums) {

        if ( nums[0] == 6 || nums[nums.length - 1] == 6 ) {

            return true;

        }

        return false;
    }

}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Marcus Vance
Author

Marcus Vance

Marcus Vance is a cybersecurity auditor and technology writer dedicated to educating the public about online safety, data privacy regulations, enterprise security, and emerging cyber threats.