gpt4 book ai didi

java - 用数组方法切换

转载 作者:行者123 更新时间:2023-11-29 07:28:33 25 4
gpt4 key购买 nike

这是我第一次使用数组,我对如何在此设置中使用数组感到困惑。我尝试使用 switch,但我不确定它如何使用不同的情况等。当涉及到使用 [] 的数组时,也不确定 java 知道或不知道什么。谁能告诉我我的想法是否正确,或者我是否完全不对。

public class Sum3 {
// TODO - write your code below this comment.
// You will need to write a method that will take
// an array of int, and will return the sum of
// the first three elements. NOTE THAT
// THE ARRAY LENGTH MAY BE SMALLER THAN 3.
// In the event that the array isn't long enough,
// substitute 0s for the missing elements.
// For example:
// - if the array is empty you should return 0 (0 + 0 + 0 = 0),
// - if the array contains only one element, you should
// return that element (element + 0 + 0 = element)
// - if the array contains only two elements, you
// should return the sum of those two elements
// (first + second + 0 = first + second)
// - if the array contains three or more elements,
// you should return the sum of the first three.
//
// You may be given an array which holds more than
// three elements. These extra elements (beyond three)
// should be ignored.
//
// As a hint, switch may be useful here (though you
// are not required to use it).
//
public static int array(int[] array) {
switch (array) {
case 0:
return 0;
case 1:
return ([0]);
case 2:
return ([0]+[1]);
case 3:
return ([0]+[1]+[2]);

// DO NOT MODIFY main!
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int[] array = new int[3];
System.out.print("Enter first integer: ");
array[0] = input.nextInt();
System.out.print("Enter second integer: ");
array[1] = input.nextInt();
System.out.print("Enter third integer: ");
array[2] = input.nextInt();
System.out.println("Sum: " + sumUpToFirst3(array));
}
}

最佳答案

它甚至看起来不像您粘贴的代码可以编译,但这里是 sumUpToFirst3 的一个简单实现,我认为它应该可以工作:

public int sumUpToFirst3(int[] array) {
if (array == null) {
return 0;
}

int upperBound = array.length > 3 ? 3 : array.length;
int sum = 0;

for (int i=0; i < upperBound; ++i) {
sum += array[i];
}

return sum;
}

关于java - 用数组方法切换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46617014/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com