[2021 Spring] CS61B 课后练习 HW 0: A Java Crash Course
2021/7/17 17:35:47
本文主要是介绍[2021 Spring] CS61B 课后练习 HW 0: A Java Crash Course,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
hw0: https://sp21.datastructur.es/materials/hw/hw0/hw0
hw0简单介绍了Java的基本语法,与python等其他语言的对比,了解java基础可以跳过。
- Creative Exercise 1a: Drawing a Triangle
- Creative Exercise 1b: DrawTriangle
- Exercise 2
- Exercise 3
- Exercise 4
Creative Exercise 1a: Drawing a Triangle
public class Ex1a { public static void main(String[] args) { Draw(5); } public static void Draw(int x) { int y = 1; while (y <= x) { int i = 0; while (i < y) { System.out.print('*'); i++; } System.out.println(); y++; } } }
Creative Exercise 1b: DrawTriangle
public class Ex1b { public static void main(String[] args) { drawTriangle(10); } public static void drawTriangle(int N) { int x = 1; while (x <= N) { int i = 0; while (i < x) { System.out.print('*'); i++; } System.out.println(); x++; } } }
Exercise 2
public class Ex2 { /** Returns the maximum value from m. */ public static int max(int[] m) { int maxNumber = 0; int i = 0; while (i < m.length) { if (maxNumber < m[i]) { maxNumber = m[i]; } i++; } return maxNumber; } public static void main(String[] args) { int[] numbers = new int[]{9, 2, 15, 2, 22, 10, 6}; System.out.println(max(numbers)); } }
Exercise 3
public class Ex3 { /** Returns the maximum value from m using a for loop. */ public static int max(int[] m) { int maxNumber = 0; for (int i = 0; i < m.length; i++) { if (maxNumber < m[i]) { maxNumber = m[i]; } } return maxNumber; } public static void main(String[] args) { int[] numbers = new int[]{9, 2, 15, 2, 22, 10, 6}; System.out.println(max(numbers)); } }
Exercise 4
public class Ex4 { public static void windowPosSum(int[] a, int n) { /** your code here */ for (int i = 0; i < a.length; i++) { if (a[i] < 0) { continue; } if (i == a.length - 1) { break; } for (int j = 1; j <= n; j++) { if (i + j >= a.length){ break; } a[i] = a[i] + a[i + j]; } } } public static void main(String[] args) { int[] a = {1, 2, -3, 4, 5, 4}; int n = 3; windowPosSum(a, n); // Should print 4, 8, -3, 13, 9, 4 System.out.println(java.util.Arrays.toString(a)); } }
这篇关于[2021 Spring] CS61B 课后练习 HW 0: A Java Crash Course的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-09-28微服务架构中API版本控制的实践
- 2024-09-28AI给的和自己写的Python代码,都无法改变输入框的内容,替换也不行
- 2024-09-27Sentinel配置限流资料:新手入门教程
- 2024-09-27Sentinel配置限流资料详解
- 2024-09-27Sentinel限流资料:新手入门教程
- 2024-09-26Sentinel限流资料入门详解
- 2024-09-26Springboot框架资料:初学者入门教程
- 2024-09-26Springboot框架资料详解:新手入门教程
- 2024-09-26Springboot企业级开发资料:新手入门指南
- 2024-09-26SpringBoot企业级开发资料新手指南