开始刷CS61B啦。。还是加深一下基础加上外加学一下java
HW0很简单,就是记录一下笔记以及贴个代码
1、HW0
- java中语法段要写在{}中,且不像python,java中缩进没有functional意义。因此,下图程序面对x为正数时不能输出正确结果。
public class PrintAbsoluteValue {
public static void main(String[] args) {
int x = -5;
if (x < 0)
System.out.println("I should negate X");
x = -x;
System.out.println(x);
}
}
- exercise 1a
public class my {
public static void main(String[] args) {
int x = 0;
int j = 0;
while (x<5){
j=0;
while(j<=x){
System.out.print("*");
j = j+1;
}
System.out.println();
x = x+1;
}
}
}
-
java中方法有明确的返回类型
-
1b
public class my {
public static void drawtriangle(int n){
int j = 0;
int x = 0;
while (x<n){
j=0;
while(j<=x){
System.out.print("*");
j = j+1;
}
System.out.println();
x = x+1;
}
}
public static void main(String[] args) {
drawtriangle(10);
}
}
- array写法:
int[] numbers = new int[]{4, 7, 10};
- numbers.length返回长度
- exercise2
public class my {
public static int max(int[] m) {
int n = m.length;
int i =0;
int max = 0;
while(i<n){
if (m[i]>max){
max = m[i];
}
i = i+1;
}
return max;
}
public static void main(String[] args) {
int[] numbers = new int[]{9, 2, 15, 2, 22, 10, 6};
int v = max(numbers);
System.out.println(v);
}
}
- exercise4
public class my {
public static void windowPosSum(int[] a, int n) {
/** your code here */
int tmp =0;
for (int i = 0 ; i<a.length; i +=1){
tmp = a[i];
if (a[i]<0){
continue;
}
for (int j = i+1 ; j <= i+n; j +=1){
if (j>a.length-1){
break;
}
tmp += a[j];
}
a[i] = tmp;
}
}
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));
}
}
- loop的改进:
- for(num:i) ==== for i in s
2、类
- main函数是为了run a class的,不是所有类均有main函数
public class Dog {
public static void makeNoise() {
System.out.println("Bark!");
}
}
public class DogLauncher {
public static void main(String[] args) {
Dog.makeNoise();
}
}
-
dog class不含有main 函数,而是doglauncher类调用dog 类中的bark方法。DogLauncher是 Dog 类的客户端(客户端client是指一个类用另一个类)
-
dog类具有实例变量(非静态变量),他们必须在类内部声明;类内部不具有static关键词的方法叫做实例方法(非静态方法)
-
如果一个方法要由实例发起,则他必须是非静态的
public class Dog {
public int weightInPounds; #实例变量
public Dog(int w) { #构造器
weightInPounds = w;
}
public void makeNoise() { #实例方法
if (weightInPounds < 10) {
System.out.println("yipyipyip!");
} else if (weightInPounds < 30) {
System.out.println("bark. bark.");
} else {
System.out.println("woof!");
}
}
}
- 调用实例方法,必须要new一个新的实例对象
- 类的变量和方法都作为类的成员,可通过.调用
- 静态方法:类方法,由类调用,无需实例
实例方法:只能由实例调用 - this 关键字,表征该实例自己
- 静态变量:类固有的property,属于类: public static Dog variblename