Program
public class HelloWorld {
public static void main(string[] args) {
System.out.println("Hello World");
}
}
- All Java code must be in a class. 所有的Java代码必须在类中。
- When a Java program is executed, it runs the
public static void main(String[] args)
method. 当Java程序执行时,必须运行main方法。(main提供了类中代码的执行入口,同样test也提供了类中代码的执行入口,main和test是并列关系,并不冲突。Use the main method and the tests and confirm that your code is fully correct. 我们可以直接使用类中的方法,或在执行入口中实例化类,调用其属性或方法) - In Java, functions have a specificreturn type that comes before the function name. Functions also specify their arguments’ type. When a function returns nothing, it has a return type of
void
(print,return [type]
).
Language Constructs
Types
Primitive types
-
double
: Deciml values. -
char
: Javachar
represents a single character, and uses single quotes ('). -
char.toString()
返回字符的字符串形式
-
int
-
boolean
Reference type
Each primitive has a corresponding reference type.
Double
String
: JavaString
s use double quotes (").Character
Integer
Boolean
If you are using "generics"泛型 to declare a data structure, you must use the reference type.
null
Any reference type can be assigned a value of null
.
If we try to access an instance 实例member or call an instance method from a value of null
, we will see an error called a NullPointerException
.
数据类型转换
从低级到高级:byte
, short
(16), char
-> int
(32)-> long
-> float
(32) -> double
(64)
自动类型转换
位数低的数据类型可以自动转换为位数高的数据类型
public class ZiDongLeiZhuan {
public static void main(String[]args) {
char c1 = 'a';
int i1 = c1; // char自动类型转换为int
System.out.println("char自动类型转换为int后的值等于"+i1):
int i2 = c1 + 1; // char和int计算后的值为int类型
}
}
强制类型转换
容量大的类型转换为容量小的类型时必须使用强制类型转换
格式:(type)value
public class QiangZhiZhuanHuan {
public static void main (String[] args) {
int i = 1;
char c = (char)('a' + 1) // b
for Loop
// counting up
for (int i = 0; i < 10; i ++) {
System.out.println(i);
}
// counting down
for (int i = 9; i >= 0; i --) {
System.out.println(i);
}
// syntax
for (initialization; termination; increment) {
// loop body
}
Conditionals
&& || ! ==
String
方法
char charAt(int index)
返回指定索引处的char值boolean equals(Object anObject)
将此字符串与制定的对象比比较
int sLength = s.length();
String substr = s.substring(1, 5);
string1.concat(string2); // 连接字符串
string1 + string2;
char c = s. charAt(2);
if (s.indexOf("hello") != -1) { // 判断字符串中是否存在某子串
System.out.println("\"hello\" in s")
}
for (int i = 0; i < s.length(); i++) { // 遍历字符串中的每个字符
char letter = s.charAt(i);
System.out.println(letter);
}
String.valueOf(int i) // 返回int参数的字符串表示形式
Integer.parseInt(String s) // 将字符串转换为十进制整数
- 如何修改String中某个位置的字符?
String无法修改具体字符,转换为StringBuilder即可
StringBuilder patternB = new StringBuilder(pattern);
for (int i = 0; i < chosenWord.length(); i ++){
if (chosenWord.charAt(i) == letter) {
patternB.setCharAt(i, letter); ;
}
}
pattern = patternB.toString();
String[] split(String regex) // 将此字符串拆分给给定regular expression分隔正则表达式的匹配项。
String s = "boo:and:foo".split(":")
// s returned is: {"boo", "and", "foo"}
static String.join(CharSequence delimiter, CharSequence... elements) // 返回由CharSequence elements 的副本组成的新String,该副本与指定的delimiter的副本连接在一起
String message = String.join("-", "Java", "is", "cool");
// message returned is: "Java-is-cool"
List (resizable)
- Java has the
list
interface. We largely use theArrayList
implementation. - The
list
interface is parameterized by the type it holds, using the angle brackets<
and>
. List
s, again, do not support slicing or negative indexing.
List<String> lst = new ArrayList<>();
lst.add("zero");
lst.add("one");
lst.set(0, "sed");
System.out.println(lst.get());
System.out.println(lst.size());
if (lst.contains("one")) { // 判断
System.out.println("one in lst");
}
if (lst.isEmpty()) {
return new ArrayList<>();
}
for (String elem : lst) {
System.out.println(elem);
}
IntList Aside
IntList lst = new IntList(1, new IntList(2, new IntList(3, null)));
IntList lst = IntList.of(1, 2, 3) // The `of` method is a convenience method for creating `IntList`s.
System.out.println(lst.print()) // The other method `print` returns a `String` representation of an IntList.
// Output: 1 -> 2 -> 3
Dictionaries / Maps
- Java has two main implementations of
Map
interface:TreeMap
keeps its keys sorted and is fast;HashMap
has no defined order and is (usually) really fast. - In the angled brackets, we have the “key type” first, followed by he “value type”.
Map
s cannot directly be used with the:
for loop. Typically, we callkeySet
to iterate over a set of the keys.
Map<String, String> map = new HashMap<>();
map.put("hello", "hi"); //map不能初始为null(因为put和putAll用到指针),赋值可以 即map = map1
map.put("hello", "goodbye");
System.out.println(map.get("hello"));
System.out.println(map.size());
if (map.containsKey("hello")) {
System.out.println("\"hello\" in map");
}
for (String key : map.keySet()) { //遍历健
System.out.println(key);
}
map.replace(K key, V newValue);
map.get(key); //由健取值
map.putAll(Map map1); //将指定所有键/值对插入到map中,同健会覆盖值。但是map不能初始为null
Number类
parseInt()
方法用于将字符串作为有符号的十进制整数进行解析。
语法
static int parseInt(String s) // 有符号十进制字符串参数表示的整数值
static int parseInt(String s, int radix)
返回值
parseInt(int i)
使用指定基数的字符串参数表示的整数(基数可以是10,2,8
public class Test{
public static void main(String args[]){
int x =Integer.parseInt("9");
double c = Double.parseDouble("5");
int b = Integer.parseInt("444",16); // 16进制数444转换为十进制数1092(4*16^+4*16^1+4*16^0)
System.out.println(x);
System.out.println(c);
System.out.println(b);
}
}
// 输出
// 9
// 5.0
// 1092
Math类
Math类方法
xxxtypeValue()
将Number对象转换为xxx数据类型的值并返回
pow(double base, double exponent)
返回base的exponent次方
Programming Exercises
- ListExercises >
common
分析:asserThat
中应是Iterable值,res2
代码返回null
,调用res2
(null
值)的实例方法.isEmpty()
,报错NullPointerException
,因为null
不可迭代。
tips
- 注释:comand + / (Mac); ctrl + / (Windows)
- 方法详情:command/ctrl + 点击 / 鼠标悬停
- 断点:打在关键点/容易出错的点,使用断点模式,即debug
- 打印日志:如添加一句
System.out.println(I+"&"+j)
,run,打印所有循环次数。 Trick: If you are failing and don’t know where to start, you are recommended checking that adding print statements to help debug - 只做部分测试场景:可通过注释掉已通过的场景实现
- 返回空的数据结构:返回一个初始化(空)的数据结构,
return new ArrayList<>()