cs61b_WK1

本文介绍了Java编程的基础知识,包括HelloWorld程序、变量与循环、函数定义、静态类型的优势与劣势、自文档化的代码编写、类的定义与使用、静态与实例方法的区别以及数组对象的概念。深入探讨了Java的特性,如静态类型、强类型语言的特点,并对比了动态类型语言。

Introduction to Java

Essentials

Hello World

public class HelloWorld {
    public static void main(String[] args) {
        System.out.println("Hello world!");
    }
}
/*
1. All code in Java must be part of a class
2. We delimit the beginning and end of segment of code using { and }
3. All statements in Java must end in a semi-colon
4. For code to run we need public static void main(String[] args) 
*/

Running a Java Program (In terminal)

在这里插入图片描述
The most common way to execute a Java program is to run it though a sequence of two programs.

  1. Java compiler; $ javac HelloWorld.java
  2. Java interpreter; $ java HelloWorld

Variables and Loops

public class HelloNumbers {
	public static void main(String[] args) {
		int x = 0;
		while (x < 10) {
			System.out.println(x);
			x = x + 1;
		}
		// We cannot do these following statements in Java
		// x = "horse"; 
		// String x = "horse";
	}
}
/*
1. Before Java variables can be used, they must be declared.
2. Java variables must have a specific type
3. Java variables can never change
4. Types are verified before the code even runs!!!
*/

Static Typing

One of the most important features of Java is that all variables and expressions have so-called static type.Java variables can contain values of that type, and only that type. Furthermore, the type of a variable can never change.
Advantages of static typing

  • The compiler ensures that all types are compatible, making it easier for the programmer to debug their code.
  • Since the code is guaranteed to be free of type errors, users of your compiled programs will never run into type errors.
  • Every variable, parameter, and function has a declared type, making it easier for a programmer to understand and reason about code.
    disadvantages:
  • Code is more verbose
  • Code is less general. (There is a way around this in Java – generics)
String h = 5 + "horse";
// This one will succeed
// Since java is strongly typed, if you tell it h is a string, it can concatenate the the elements and give you a string
int h = 5 + "horse";
// When h is an int, it can't concatenate a number and a string and give you a number.
System.out.println(5 + "horse"); // 5horse
System.out.println(5 + " "); // 5 
System.out.println(5 + "10"); // 510
System.out.println(5 + 10); // 15
  • 动态类型语言:在运行期进行类型检查的语言,也就是在编写代码的时候可以不指定变量的数据类型,比如Python和Ruby
  • 静态类型语言:它的数据类型是在编译期进行检查的,也就是说变量在使用前要声明变量的数据类型,这样的好处是把类型检查放在编译期,提前检查可能出现的类型错误,典型代表C/C++和Java
  • 强类型语言,一个变量不经过强制转换,它永远是这个数据类型,不允许隐式的类型转换。举个例子:如果你定义了一个double类型变量a,不经过强制类型转换那么程序int b = a无法通过编译。典型代表是Java。e.g. int a = 5.3 // fail
  • 弱类型语言:它与强类型语言定义相反,允许编译器进行隐式的类型转换,典型代表C/C++

Defining Functions in Java

In java, all code is part of a class, we must define functions so that they belong to some class

public class LargeDemo {
	public static int larger(int x, int y) {
		if (x > y) {
			return x;
		}
		return y;
	}
	public static void main(String[] args) {
		System.out.println(larger(2, 4));
	}
}
/*
1. Functions must be declared as part of a class in Java. In Java, all functions are methods.
2. All parameters of a function must have a declared type and the return value of the function must have a declared type.
3. Functions in Java return only one value!
*/
  • Writing the code self-documenting that’s readable
  • javadoc

Code Style, Comments, Javadoc

  • Consistent style (spacing, variable naming, brace style, etc)
    Size (lines that are not too wide, source files that are not too long)
  • Descriptive naming (variables, functions, classes), e.g. variables or functions with names like year or getUserName instead of x or f.
  • Avoidance of repetitive code: You should almost never have two significant blocks of code that are nearly identical except for a few changes.
  • Comments where appropriate. Line comments in Java use the // delimiter. Block (a.k.a. multi-line comments) comments use /* and */.

https://sp19.datastructur.es/materials/guides/style-guide.html

Objects

Defining and Using Class

Elements in a class

  1. Instance variables/ non-static variables
  2. Static Methods and Non-static Methods
  3. Constructors

Terminologies in Class

  1. An Object in Java is an instance of any class.
  2. The Dog class has its own variables, also known as instance variables or non-static variables. These must be declared inside the class, unlike languages like Python or Matlab, where new variables can be added at runtime.
  3. The method that we created in the Dog class did not have the static keyword. We call such methods instance methods or non-static methods.
  4. To call the makeNoise method, we had to first instantiate a Dog using the new keyword, and then make a specific Dog bark. In other words, we called d.makeNoise() instead of Dog.makeNoise()
  5. Once an object has been instantiated, it can be assigned to a declared variable of the appropriate type, e.g. d = new Dog();
  6. Variables and methods of a class are also called members of a class.
  7. Members of a class are accessed using dot notation.在这里插入图片描述
    在这里插入图片描述

Static vs. Non-Static Methods

1. Static Method
public class Dog {
    public static void makeNoise() {
        System.out.println("Bark!");
    }
}
// We cannot: $ java Dog, because there is no main method
// To actually run the class, we'd either need to add a main method to the Dog class, as we saw in chapter 1.1. 
//Or we could create a separate DogLauncher class that runs methods from the Dog class.
public class DogLauncher {
    public static void main(String[] args) {
        Dog.makeNoise();
    }
}
// $ java DogLauncher

A class that uses another class is sometimes called a “client” of that class, i.e. DogLauncher is a client of Dog.
Neither of the two techniques is better: Adding a main method to Dog may be better in some situations, and creating a client class like DogLauncher may be better in others.

2. Non-Static Methods, Instance Variables and Object Instantiation

In fact, not all dogs will make noise in the way mentioned before. So, we can create different classes to represent different dogs, e.g. TinyDog class, BigDog class and with a specific static method.

– But, classes can be instantiated, and instances can hold data.

public class Dog {
    public int weightInPounds;

    public void makeNoise() {
        if (weightInPounds < 10) {
            System.out.println("yipyipyip!");
        } else if (weightInPounds < 30) {
            System.out.println("bark. bark.");
        } else {
            System.out.println("woof!");
        }
    }    
}

public class DogLauncher {
    public static void main(String[] args) {
        Dog d;
        d = new Dog();
        d.weightInPounds = 20;
        d.makeNoise();
    }
}

Arrays of Objects

Dog[] dogs = new Dog[2]; // No Dog objects are created in that statement
// just like constructing two dog houses that are currently empty
dogs[0] = new Dog(8);

“new” is used in two different ways:

  1. Once to create an array that can hold two Dog objects;
  2. Twice to create each actual Dog

Static vs. Non-static (Class Methods vs. Instance Methods)

Java allows us to define two types of methods:
1. Class methods, a.k.a. static methods
Static methods are actions that are taken by the class itself
2. Instance methods, a.k.a non-static methods
Instance methods are actions that can be taken only by specific instance of a class

Both are useful in different circumstances:

// Math class provides a sqrt method, which is static
int x = Math.sqrt(100);
// But if sqrt had been an instance method, we would have to create a Math instance first.

Sometimes, it makes sense to have a class with both instance methods and static methods, like comparator()

Key differences between static and non-static (a.k.a instance) method:

  • Static methods are invoked using the class name, e.g. Dog.makeNoise();
  • Instance methods are invoked using an instance name, e.g. maya.makeNoise();
  • Static methods can’t access instance variables, because there is no “me”
    Why static method?
  • Some classes are never instantiated. For example, Math.
  • Sometimes, classes may have a mix of static and non-static methods
    Static variable
    It is occasionally useful for classes to have static variables. These are properties inherent to the class itself, rather than the instance.
    All objects will have the same properties
    But if you have a static variable for a class, just use the class name rather than using the instance variable name.
    A class may have a mix of static and non-static members
  • A variable or method defined in a class is also called a member of that class
  • Static members are accessed using class name, e.g. Dog.binomen
  • Non-static members cannot be invoked using class name
  • Static members, you should really really strive to use class name
  • Static methods must access instance variable via a specific instance

public static void main(String[] args)

  • public: So far, all of our methods start with this keyword.
  • static: It is a static method, not associated with any particular instance.
  • void: It has no return type.
  • main: This is the name of the method.
  • String[] args: This is a parameter that is passed to the main method.
    Since main is called by the Java interpreter itself rather than another Java class, it is the interpreter’s job to supply these arguments. They refer usually to the command line arguments.
Request POST https://app.m.kuaishou.com/rest/wd/ztReport/user/report/aggregation/v2 HTTP/1.1 Host: app.m.kuaishou.com Accept: application/json Sec-Fetch-Site: same-origin Accept-Language: zh-CN,zh-Hans;q=0.9 Accept-Encoding: gzip, deflate, br Sec-Fetch-Mode: cors Content-Type: application/json;charset=utf-8 Origin: https://app.m.kuaishou.com User-Agent: Mozilla/5.0 (iPhone; CPU iPhone OS 18_4_1 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148 ksNebula/13.6.60.3942 ISLP/0 StatusHT/59 KDT/PHONE iosSCH/0 TitleHT/44 NetType/MOBILE_4G ISDM/0 ICFO/0 locale/zh-Hans CT/0 Yoda/3.3.8 ISLB/0 CoIS/2 ISLM/0 WebViewType/WK BHT/102 AZPREFIX/az2 Referer: https://app.m.kuaishou.com/report-v2/index.html?sourceType=user&liveStreamId=&prerefer=ks%253A%252F%252Freminder%252Fmessage%252Fmesage_detail&refer=ks%253A%252F%252Fprofile%252F3695349534%252F%2528null%2529&client_version=13.6.60.3942&reportedUserId=3695349534&os_version=18.4.1&user_id=1910744115&mobile_type=iphone&exp_tag=_&appType=nebula&entrySource=userReportShunt Content-Length: 1872 Connection: keep-alive Sec-Fetch-Dest: empty Cookie: kuaishou.sixin.login_st=ChdrdWFpc2hvdS5zaXhpbi5sb2dpbi5zdBKgAQbYzfGL0dKofl2HONKNinp_gDd6VcVT0kRo5i68lG0cmi6rG7neXac7z9POJpjyWdsREfpiglMP1EcF4wajDF4Cz7wdjUAKMDO9_E7aXBPb5JmihlWDPvFUv-h1lApYPt16bVaTsKnAos4iK0aF-SFVeMXoXDwWxtYEureY7JYsc-BeiS5E_hp9BBfX1yw9yHYp_7u68wXbJTS1VPjTiuAaEoAWmB7Xy0X7j4yzC4v3ZpXeKyIg62rchj4FsnyL5c3hRufP--3uWXy-tymyo2PT6-V5BiUoBTAB; session_id=16E86B43-EBAB-4515-8ACC-213BDA28A332; sid=16E86B43-EBAB-4515-8ACC-213BDA28A332; thermal=10010; mcc=6553565535; uQaTag=66115%2333333333339999999999%23swRs%3A09%23swLdgl%3A-9%23ecPp%3A72%23cmNt%3A11%23cmHs%3A-2%23cmMnsl%3A-0; __NSWJ=; apptype=2; appver=13.6.60.3942; bottom_navigation=1; browseType=3; c=a; cdidTag=2; cdid_tag=2; cl=0; client_key=63b2bdd7; countryCode=cn; country_code=cn; cs=false; darkMode=false; deviceBit=0; did=F9AD007F-E8B9-27CD-92EC-419BA621A49F; didTag=0; did_tag=0; egid=DFP23FEFA46D208B689E626E29D641753B30E99FDD1C026590A34E451FDB15A8; foreign=0; ftt=; gid=DFP23FEFA46D208B689E626E29D641753B30E99FDD1C026590A34E451FDB15A8; global_id=DFP23FEFA46D208B689E626E29D641753B30E99FDD1C026590A34E451FDB15A8; grant_browse_type=AUTHORIZED; isp=; kpf=IPHONE; kpn=NEBULA; kuaishou.api_st=Cg9rdWFpc2hvdS5hcGkuc3QSoAG1AIJD1Rg8u1wHvdC-7jcNxLvd7l1xIBOb6wf70EJdPHfFUX76vhbC69bvccAewuAEyQxshvpMHjhuIdzPwUqo1DkSmttotkgo2TZAAnFnf-Eypizk1oY6h8OgxTht3vfGCrAkyZEXgKWxM_HddIV0pbc9Wco_u6B7FKvq8WlggPXfSF15S-k7JA9A9BhZudLc-e5MlwkBai9ml2VkDSKaGhJThZNu-rRPH4Mw3KnOATqUKJgiILfVQEnAwvNFg7z23voyCvQaIY9b7THhP2OFoHzcAqFUKAUwAQ; kuaishou.h5_st=Cg5rdWFpc2hvdS5oNS5zdBKgAWvJ3UnuzOIMQOwv53Km7iObeq6umB5kJb2P941tlfxiY_l4V669Ck00cH02_lzR2ZppdQHqhRo0-Go2qtalo517FrDflKN26_2Fv6CDxu0FHC57mreoiICz83ne5eI1Y3Ka2V9vG987HPur2vyGa2SZQDPaidRDNHfeLbLt4pIxYSB4txbAvykK-uNMab6AALCrQv1XLczqcmGpCU-6xakaErEJA26FToVlAmaCbr6l_rMcGiIgW0cx-D11eNvEuXEjUv24C6ypirgJdob6bjyBOF77TAUoBTAB; language=zh-Hans-CN%3Bq%3D1; lat=; lkvr=; ll=; ll_client_time=0; lon=; mod=iPhone16%2C2; net=MOBILE_3G; oDid=7C57A53C-ADF6-42D2-AC5D-15CD16CF2B87; odid=7C57A53C-ADF6-42D2-AC5D-15CD16CF2B87; os=18.4.1; pUid=rA0I2agA8tb_FS3tLzpaI8AkRbze4v8e54598461d170d9b; power_mode=0; randomDid=7C57A53C-ADF6-42D2-AC5D-15CD16CF2B87; rdid=7C57A53C-ADF6-42D2-AC5D-15CD16CF2B87; sh=2796; sw=1290; sys=iOS_18.4.1; token=Cg9rdWFpc2hvdS5hcGkuc3QSoAHUOHu-Yyzv5ND8_r8iSAsH5Py6cMKJaE0StjqUL_KLKhr8hUefHi_zBrEk6HIT81LrdVp_zJ6eTUNjPOO76FKimaSMbwcwKB6rqLrDSXdk05jd1qBOXD6krV2tTKeyc2t2nyzlH-KCNS1w-lAAEwJAPmRVmAY9w4wKVwtGh4e4gvcRVKJEUboQAVMrAwQDjTcfwbjWQQ_b2ZOyH4bEq5BQGhL-n59CWGdM3bmoLtqIcC_9Za0iIKlbVtIXlQbKZQp5XvW1Oo0n-CVRIBeh4wvQUJJDWpVxKAUwAQ; ud=1910744115; urlencode_mod=iPhone16%252C2; userId=1910744115; userRecoBit=0; ver=13.6; videoModelCrowdTag=1_89; weblogger_switch=; didv=1754365221000 {"recoParams":"{\"common_log_ctx\":\"{\\\"stid_container\\\":{\\\"st_reco_stgy_id\\\":\\\"1|2004919408459855634|photo:5244441939142966873|{\\\\\\\"pg\\\\\\\":\\\\\\\"sl\\\\\\\"}|{\\\\\\\"r\\\\\\\":509,\\\\\\\"mix\\\\\\\":\\\\\\\"1_1_0_0_0\\\\\\\",\\\\\\\"f\\\\\\\":\\\\\\\"Cg4IARIDaWlkGK+B9byDBQoKCAESBmlzX3BpYwoNCAESCXN3dG5fcGF0aAoNCAESCXN3dG5faXRlbQoNCAESCXN3dG5fYmlndgoMCAMSAmJ6KgQxXzA0CgoIARIEZGFjdBgCCg0IARIFcnNjbnQY5\\\\/8\\\\/\\\\\\\"}\\\",\\\"st_reco_id\\\":\\\"1|2004919686168731666|photo:5256545361903922590|{\\\\\\\"pg\\\\\\\":\\\\\\\"slp\\\\\\\"}|{\\\\\\\"r\\\\\\\":0}\\\"},\\\"st_merge_array\\\":[\\\"st_reco_stgy_id,st_reco_id\\\"]}\"}","sourceType":"user","liveStreamId":"","prerefer":"ks%3A%2F%2Freminder%2Fmessage%2Fmesage_detail","refer":"ks%3A%2F%2Fprofile%2F3695349534%2F%28null%29","client_version":"13.6.60.3942","reportedUserId":"3695349534","os_version":"18.4.1","user_id":"1910744115","mobile_type":"iphone","exp_tag":"_","appType":"nebula","entrySource":"userReportShunt","reportType":206,"illegalContent":[8,7],"leadToFraud":true,"hasFraudConfirm":false,"descriptionPasteContent":"","descriptionIsPaste":0,"descriptionInputNum":0,"detail":"发不pi","imageIds":[],"jsonExtParams":"{\"referUrl\":\"{\\n \\\"page\\\": \\\"MESSAGE_DETAIL\\\",\\n \\\"sub_pages\\\": \\\"ks://reminder/message/mesage_detail\\\",\\n \\\"params\\\": \\\"subbiz_params=(null)&sub_biz=0&receive_user_id=3695349534&is_half=false&expert_biz_type=(null)&chat_page_source=4&cny25_entry_source=\\\",\\n \\\"identity\\\": \\\"BF553E16-8C09-472B-9F2C-F88537517C47\\\",\\n \\\"page_seq\\\": 422,\\n \\\"page2\\\": \\\"MESSAGE_DETAIL\\\",\\n \\\"top_page\\\": \\\"MESSAGE\\\",\\n \\\"top_page_session_id\\\": 564979\\n}\",\"referElement\":\"{\\n \\\"action2\\\": \\\"USER_HEAD\\\"\\n}\",\"reportEntryTime\":1755534787848,\"reportSubmitTime\":1755534796235}","expTag":"_"} -------------------------------------------------------- Response HTTP/1.1 200 Date: Mon, 18 Aug 2025 16:33:16 GMT Content-Type: application/json;charset=UTF-8 Connection: keep-alive Content-Encoding: gzip X-KSLOGID: 755534796362547527 X-KSClient-IP: 112.97.166.96 Content-Length: 623 {"result":1,"countInfo":{"helpPersonCount":330,"reportCountMonth":102,"reportCountAhead":0.9989717128838086},"reportedUser":{"following":true,"eid":"3xce499z2wwb9ae","headurls":[{"cdn":"p2-pro.a.yximgs.com","url":"https://p2-pro.a.yximgs.com/uhead/AB/2025/05/19/22/BMjAyNTA1MTkyMjM3MzVfMzY5NTM0OTUzNF8yX2hkNjA4XzYwMQ==_s.jpg"},{"cdn":"p1-pro.a.yximgs.com","url":"https://p1-pro.a.yximgs.com/uhead/AB/2025/05/19/22/BMjAyNTA1MTkyMjM3MzVfMzY5NTM0OTUzNF8yX2hkNjA4XzYwMQ==_s.jpg"}],"visitorBeFollowed":false,"profilePagePrefetchInfo":{"profilePageType":1},"user_name":"̖́\uD83D\uDD77","headurl":"https://p2-pro.a.yximgs.com/uhead/AB/2025/05/19/22/BMjAyNTA1MTkyMjM3MzVfMzY5NTM0OTUzNF8yX2hkNjA4XzYwMQ==_s.jpg","user_id":3695349534,"user_sex":"F"},"reportActivityLink":"https://ppg.m.etoote.com/doodle/o/CEiaenwm.html","operationInfo":{"urlText":"举报处理流程","url":"http://www.gifshow.com/s/RLfmOzdQ"},"csLogCorrelateInfo":{"id":"2f24a0ec-9ad4-be4f-21a0-b673e7684b85","type":"USER_REPORT_RESULT"},"host-name":"public-bjy-c26-kce-node1278.idchb1az2.hb1.kwaidc.com","enableReportCenter":true} 帮我写成快手封号代码py按照我提供的代码写
08-20
内容概要:本文系统介绍了算术优化算法(AOA)的基本原理、核心思想及Python实现方法,并通过图像分割的实际案例展示了其应用价值。AOA是一种基于种群的元启发式算法,其核心思想来源于四则运算,利用乘除运算进行全局勘探,加减运算进行局部开发,通过数学优化器加速函数(MOA)和数学优化概率(MOP)动态控制搜索过程,在全局探索与局部开发之间实现平衡。文章详细解析了算法的初始化、勘探与开发阶段的更新策略,并提供了完整的Python代码实现,结合Rastrigin函数进行测试验证。进一步地,以Flask框架搭建前后端分离系统,将AOA应用于图像分割任务,展示了其在实际工程中的可行性与高效性。最后,通过收敛速度、寻优精度等指标评估算法性能,并提出自适应参数调整、模型优化和并行计算等改进策略。; 适合人群:具备一定Python编程基础和优化算法基础知识的高校学生、科研人员及工程技术人员,尤其适合从事人工智能、图像处理、智能优化等领域的从业者;; 使用场景及目标:①理解元启发式算法的设计思想与实现机制;②掌握AOA在函数优化、图像分割等实际问题中的建模与求解方法;③学习如何将优化算法集成到Web系统中实现工程化应用;④为算法性能评估与改进提供实践参考; 阅读建议:建议读者结合代码逐行调试,深入理解算法流程中MOA与MOP的作用机制,尝试在不同测试函数上运行算法以观察性能差异,并可进一步扩展图像分割模块,引入更复杂的预处理或后处理技术以提升分割效果。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值