第一范文网 - 专业文章范例文档资料分享平台

面向对象编程基础习题及答案

来源:用户分享 时间:2025/5/23 21:06:21 本文由loading 分享 下载这篇文档手机版
说明:文章内容仅供预览,部分内容可能不全,需要完整文档或者需要复制内容,请下载word后使用。下载word有问题请添加微信号:xxxxxxx或QQ:xxxxxx 处理(尽可能给您提供完整文档),感谢您的支持与谅解。

int sum = 0;

+1pt +1pt +2pt +2pt

while (number != 0) { sum += number % 10; number = number / 10; }

return sum; }

+1pt

6. (8pts) Write a method that computes the average of the values in an array of doubles. The

header of the method is as follows:

public static double average(double[] x)

Referenced Code:

public static double average(double[] x) { double total = 0;

for (int i = 0; i < x.length; i++) total += x[i];

+1pt +2pt +1pt +2pt +2pt

return total / x.length; }

7. (8pts) Write a method that returns the index of the smallest element in an array of integers. If

there are more than one such elements, return the smallest index.

public static int minIndex(int[] list)

Referenced Code:

public static int minIndex(int[] list) { int min = list[0]; int minIndex = 0;

+1pt +1pt +1pt +1pt +1pt +1pt +1pt +1pt

for (int i = 1; i < list.length; i++) if (min > list[i]) { min = list[i]; minIndex = i; }

return minIndex; }

8. (15pts): Write a method that returns a new array with no duplicates. For example, if x is {1, 3,

1, 2, 3, 5}, removeDuplicate(x) returns a new array {1, 3, 2, 5}. The header of the method is

第 33 页 共 34 页

as follows:

public static int[] removeDuplicate(int[] x)

Referenced Code:

public static int[] removeDuplicate(int[] x) { int[] temp = new int[x.length]; int tempSize = 0;

for (int i = 0; i < x.length; i++) { // Check if x[i] is already in temp boolean duplicate = false;

for (int j = 0; j < tempSize; j++) if (x[i] == temp[j]) duplicate = true;

if (!duplicate) { // Add x[i] into temp

temp[tempSize] = x[i]; tempSize++;

}

}

int[] result = new int[tempSize]; System.arraycopy(temp, 0, result, 0, tempSize); return result;

}

第 34 页 共 34 页

+1pt +1pt +1pt +1pt +1pt +1pt +1pt +1pt +1pt +1pt +1pt

+1pt +2pt +1pt

搜索更多关于: 面向对象编程基础习题及答案 的文档
面向对象编程基础习题及答案.doc 将本文的Word文档下载到电脑,方便复制、编辑、收藏和打印
本文链接:https://www.diyifanwen.net/c8zw199vcmo44p5d1brid_9.html(转载请注明文章来源)
热门推荐
Copyright © 2012-2023 第一范文网 版权所有 免责声明 | 联系我们
声明 :本网站尊重并保护知识产权,根据《信息网络传播权保护条例》,如果我们转载的作品侵犯了您的权利,请在一个月内通知我们,我们会及时删除。
客服QQ:xxxxxx 邮箱:xxxxxx@qq.com
渝ICP备2023013149号
Top