[英]CodingBat - Java - Array1 - firstLast6 - how to call the boolean method with an array as a parameter
我希望一切都好。 我最近在 Coding Bat (Java - Array1 - firstLast6) 中解决了一个算法:
问题
*给定一个整数数组,如果 6 出现在数组中的第一个或最后一个元素,则返回 true。 该数组的长度将为 1 或更多。
firstLast6([1, 2, 6]) → 真
firstLast6([6, 1, 2, 3]) → 真
firstLast6([13, 6, 1, 2, 3]) → false*
我的解决方案
public boolean firstLast6(int[] nums) {
if ( (nums[0] == 6) || (nums[nums.length - 1]) == 6 ) {
return true;
}
return false;
}
这是正确的解决方案。 但是,在 Coding Bat 中解决问题是一回事,但我希望能够在我的 VS Code 编辑器中的 main 方法中调用这个 boolean 方法。 因此,我的研究并没有为我的问题提供可靠的答案。
在主要方法中:
Boolean 方法调用:如何调用以数组 (nums) 作为参数的 boolean 方法? 我坚持这部分的语法。
打印语句:使用“System.out.println()”打印出真假结果?
VS 代码 - 完整布局
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;
}
}
你可以做:
public static void main(String[] args) {
System.out.println(fistLast6(new int[] {1, 2, 6}));
}
和@thinkgruen 的建议:
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;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.