简体   繁体   中英

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;
    }

}

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;
}
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;
    }

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM