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