Java_note

Java Note

输入输出

普通输入输出

nextInt()和next()都会自动跳过前面遗留的结束符(空格键、Tab键或Enter键

而nextLine()会读取遗留的结束符

单变量

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
import java.util.Scanner

public class Main {
public static void main(String[] args) {
Scanner cin = new Scanner(System.in);
int nu = cin.nextInt(); //int类型
System.out.println(nu);
float fl = cin.nextFloat(); //float类型
double dou = cin.nextDouble(); //double类型
char change = cin.next().charAt(0); //char类型
String str = cin.next(); //String类型,遇到空格结束
String st = cin.nextLine(); //String类型,读取一行数据,遇到换行结束。类似gets
cin.close();
}
}

输入数据个数或行数未知

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
import java.util.Scanner;

public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
while (sc.hasNextInt()) {
int num = sc.nextInt();
System.out.println(num);
}
sc.nextLine(); // 读取数字后面的换行
while (sc.hasNextLine()) {
String str = sc.nextLine();
System.out.println(str);
}
}
}

逗号分隔的数组

input: 5 11,12,13,14,15

output: 11,12,13,14,15

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
import java.util.Scanner;

public class Main {
public static void main(String[] args) {
// 1.new一个 Scanner 对象
Scanner sc = new Scanner(System.in);

// 2.整数使用 nextInt();
int n = sc.nextInt();

// 3.nextLine()表示读取一行作为字符串,这里读取 n 后面的换行符
sc.nextLine();

int[] nums = new int[n];
// 4.数组作为一个字符串输入,并按照逗号切分,每个数字以 String 类型存储
// 4.1 扩展:sc.next()也是读取字符串,但是不是以换行分割,而是以空格分割
String[] input = sc.nextLine().split(",");

// 5.String 转 int
for (int i = 0; i < n; i++) {
nums[i] = Integer.parseInt(input[i]);
}

// 6.输出。print()仅输出内容,println输出内容并换行
for (int i = 0; i < n; i++) {
System.out.print(nums[i]);
if (i != n - 1) System.out.print(",");
else System.out.print("\n");
}
}
}

格式化输出

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
import java.text.DecimalFormat;

public class Main {
public static void main(String[] args) {
// 方法一:String的format方法(推荐)
double f = 111231.5585;
// 保留 2 位小数(有四舍五入)
System.out.println(String.format("%.2f", f));

// 方法二:DecimalFormat的format方法
double f = 111231.5585;
DecimalFormat df = new DecimalFormat("#.00");
System.out.println(df.format(f));
}
}

快速输入输出

BufferedReader/Writer

  • read() 方法用于读取单个字符,返回该字符的整数表示(即字符的 Unicode值)。如果到达流的末尾,返回 -1。

  • write() 不能直接输出int类型, 因为write(int a) 会输出其对应的ASCii码的字符

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
import java.io.*;

public class Main {
public static void main(String[] args) throws Exception {
BufferedReader cin = new BufferedReader(new InputStreamReader(System.in));
BufferedWriter cout = new BufferedWriter(new OutputStreamWriter(System.out));
int a1 = 66;
int b = cin.read(); // read()只读取一个字符
int c = cin.read(); // 吸收 \n
int x = cin.read();
String d = cin.readLine();
// readLine()会将"\n\r"全部吸收,所以只需要一个readLine()来吸收回车
cout.write(Integer.toString(a1));
cout.write("\n");
cout.write(b + "\n");
cout.flush(); // 此时才会真正触发输出
cin.close();
}
}

StreamTokenizer/PrintWriter

  • StreamTokenizer只能接收数字或字母,如果输入除空格和回车以外的字符(如:!@#$%^&*())无法识别,会显示null。
  • 如果标记是字符串,用st.sval获取标记,如果是数字用st.nval获取标记,st.navl是double类型。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
import java.io.*;

public class Main {
public static StreamTokenizer cin = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in)));
public static PrintWriter cout = new PrintWriter(new OutputStreamWriter(System.out));

public static void main(String[] args) throws Exception {
int n = nextInt();
long m = nextLong();
double d = nextDouble();
cout.println(n);
cout.println(m);
cout.println(d);
cout.flush();

closeAll();
}

public static int nextInt() throws Exception{
cin.nextToken();
return (int) cin.nval;
}
public static long nextLong() throws Exception{
cin.nextToken();
return (long) cin.nval;
}
public static double nextDouble() throws Exception{
cin.nextToken();
return cin.nval;
}
public static String nextString() throws Exception{
cin.nextToken();
return cin.sval;
}
public static void closeAll() throws Exception {
cout.close();
in.close();
out.close();
}

}

多组输入

1
2
3
4
5
6
7
8
9
10
11
12
public static void main(String[] args) throws Exception {
StreamTokenizer in = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in)));
PrintWriter out = new PrintWriter(new OutputStreamWriter(System.out));

while (in.nextToken() != StreamTokenizer.TT_EOF){
int n = (int) in.nval;
in.nextToken();
int m = (int) in.nval;
out.println(n+" "+m);
out.flush();
}
}

数组

1
2
3
4
5
6
dataType[] arrayRefVar = new dataType[arraySize];
dataType[][] arrayRefVar = new dataType[arraySize][arraySize];

int[] arr1 = new int[]{1,2,3,4,5};

Arrays.fill(Type[] array, int startIndex, int endIndex, Type value) //数组填充默认值

复制数组

1
2
3
System.arraycopy(int[] src, int start1,int[] dest, int start2, length);

int[] new_array = Arrays.copyOf(int[] srcArray,int new_length);

截取数组

1
int[] new_array = Arrays.copyOfRange(src,start,end);//左闭右开

哈希表

HashMap

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
Map<Integer, String> map= new HashMap<Integer, String>();
map.put(1, "string1");
String value = map.replace(2, "Wiki");

map.get(1);
// 找不到,返回null
map.getOrDefault(Object key, V defaultValue)
// 找不到key,返回defaultValue


//遍历
for (Map.Entry<Integer, String> entry : map.entrySet()) {
Integer key = entry.getKey();
String value = entry.getValue();
}
// 迭代键
for (Integer key : map.keySet()) {
System.out.println("Key = " + key);
}
// 迭代值
for (Integer value : map.values()) {
System.out.println("Value = " + value);
}

//lambda遍历
map.forEach((key, value) -> {
System.out.println("Key: " + key + ", Value: " + value);
});
方法 描述
clear() 删除 hashMap 中的所有键/值对
clone() 复制一份 hashMap
isEmpty() 判断 hashMap 是否为空
size() 计算 hashMap 中键/值对的数量
put() 将键/值对添加到 hashMap 中
putAll() 将所有键/值对添加到 hashMap 中
putIfAbsent() 如果 hashMap 中不存在指定的键,则将指定的键/值对插入到 hashMap 中。
remove() 删除 hashMap 中指定键 key 的映射关系
containsKey() 检查 hashMap 中是否存在指定的 key 对应的映射关系。
containsValue() 检查 hashMap 中是否存在指定的 value 对应的映射关系。
replace() 替换 hashMap 中是指定的 key 对应的 value。
replaceAll() 将 hashMap 中的所有映射关系替换成给定的函数所执行的结果。
get() 获取指定 key 对应对 value
getOrDefault() 获取指定 key 对应对 value,如果找不到 key ,则返回设置的默认值
forEach() 对 hashMap 中的每个映射执行指定的操作。
entrySet() 返回 hashMap 中所有映射项的集合集合视图。
keySet() 返回 hashMap 中所有 key 组成的集合视图。
values() 返回 hashMap 中存在的所有 value 值。

HashSet

1
2
3
4
5
6
7
8
9
Set<Integer> hashset= new HashSet<Integer>();
hashset.add(1);
hashset.contains(1); //判断元素是否存在
hashset.remove(1);
hashset.clear();
hashset.size()
for (int number : hashset) {
//遍历
}

List

在Java中实现List接口的类

ArrayList

1
2
List<String> list1 = new ArrayList<>();
List<String> list2 = new ArrayList<String>(Arrays.asList("apple", "banana", "orange"));
  • add() - 将元素添加到列表
  • addAll(ArrayList) - 将一个列表的所有元素添加到另一个
  • get(index) - 有助于从列表中随机访问元素
  • set(index, element) - 更改列表的元素
  • remove(Object obj) - 从列表中删除一个元素
  • remove(int index) - 从列表中删除一个元素
  • clear() - 从列表中删除所有元素(比removeAll()效率更高)
  • size() - 返回列表的长度
  • contains() - 如果列表包含指定的元素,则返回true
  • indexOf()
  • isEmpty()

Stack

1
Stack<Type> stacks = new Stack<>();
  • Object push()
  • Object pop()
  • int search(Object)
  • boolean isEmpty()
  • Object peek( )

Queue

ArrayDeque双端队列

1
Deque<Type> animal = new ArrayDeque<>();
  • add()/addLast()

    addFirst()

  • boolean offer()/offerLast()

    boolean offerFirst()

    成功插入元素,返回true;如果双端队列已满,返回false

  • Object getFirst()/peek()

    Object getLast()

  • removeFirst()/remove()

    删除第一个元素,并返回删除元素的值,如果元素为null,将抛出异常 pollFirst()/poll()

    删除第一个元素,并返回删除元素的值,如果元素为null,将返回null removeLast()

    删除最后一个元素,并返回删除元素的值,如果为null,将抛出异常 pollLast()

    删除最后一个元素,并返回删除元素的值,如果为null,将返回null

    removeFirstOccurrence(Object o)

    删除第一次出现的指定元素

    removeLastOccurrence(Object o)

    删除最后一次出现的指定元素

  • size() 获取队列中元素个数

  • isEmpty() 判断队列是否为空

  • contain(Object o) 判断队列中是否存在该元素

  • toArray() 转成数组

  • clear() 清空队列

  • 栈操作

    push(E e) 栈顶添加一个元素

    pop(E e) 移除栈顶元素,如果栈顶没有元素将抛出异常

PriorityQueue优先级队列

默认小根堆

1
2
Queue<Integer> queue = new PriorityQueue<>();
Queue<Integer> queue = new PriorityQueue<>(k); //size为k的最小堆
  • add()/offer()

  • peek()

  • remove()/poll()

  • contains()

  • size()

  • toArray()

  • 比较器

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    //lambda
    PriorityQueue<Integer> pq = new PriorityQueue<>(k, ((o1, o2) -> {return o2 - o1;}));

    //常规写法
    PriorityQueue<Integer> pq = new PriorityQueue<>(new Comparator<Integer>() {
    @Override
    public int compare(Integer o1, Integer o2) {
    return o2 - o1;
    }
    });

Arrays

判断数组相等

Arrays.equals(ary, ary1)

排序

Arrays.sort(s[,Comparator])

  • 针对数据类型(基本数据类型和引用对象类型)的数组元素
  • 自定义排序Comparator
1
2
3
4
5
6
7
8
9
10
11
12
13
Comparator<student> comparatorAge =new Comparator <student>(){
@Override
public int compare(student p1,student p2){
if (p1.getAge()>p2.getAge())
return 1;
else if (p1.getAge()<p2.getAge())
return -1;
else
return 0;
}
};

Arrays.sort(s,comparatorAge);

Collections

sort

Collections.sort(s[,Comparator])

  • 针对集合框架中的动态数组,链表,树,哈希表等
  • 自定义排序Comparator
1
2
3
4
5
6
7
8
Collections.sort(people, new Comparator<Person>() { 
@Override
public int compare(Person p1, Person p2) {
// 按照年龄升序排序
return p1.getAge() - p2.getAge();
}
});

在Comparator接口的compare方法中,返回值遵循以下约定:

  • 返回值小于0,第一个对象(o1)排在第二个对象(o2)之前。
  • 返回值等于0,则表示两个对象是相等的,它们的顺序无关紧要。
  • 返回值大于0,第一个对象(o1)排在第二个对象(o2)之后。
lambda表达式比较(Java 8)
1
Collections.sort(people, (p1, p2) -> p1.getAge() - p2.getAge());

reverse

Collections.reverse(list);

shuffle

Collections.shuffle(list);

max

Collections.max(list)/min(list);

swap

Collections.swap(list,3,4);

String

  • s.length()

    length不是方法,是数组的属性

    length()是字符串String的一个方法

  • string1.concat(string2);

  • 格式化

    1
    2
    3
    4
    5
    String fs;
    fs = String.format("浮点型变量的值为 " +
    "%f, 整型变量的值为 " +
    " %d, 字符串变量的值为 " +
    " %s", floatVar, intVar, stringVar);
  • char charAt(int index)

  • boolean equals(Object anObject)

  • int compareTo(String anotherString)

    • 如果参数字符串等于此字符串,则返回值 0;
    • 如果此字符串小于字符串参数,则返回一个小于 0 的值;
    • 如果此字符串大于字符串参数,则返回一个大于 0 的值。
  • boolean endsWith(String suffix)

  • boolean startsWith(String prefix, [int toffset])

  • String replace(char searchChar, char newChar)

  • String substring(int beginIndex, int endIndex)

  • String toLowerCase()

  • String toUpperCase()

  • boolean contains(CharSequence chars)

  • char[] toCharArray()

  • String.valueOf(char[] data) : 将char转换成字符串

  • String trim()

  • boolean isEmpty()

index

  • int indexOf(int ch): 返回指定字符在字符串中第一次出现处的索引,如果此字符串中没有这样的字符,则返回 -1。
  • int indexOf(int ch, int fromIndex): 返回从 fromIndex 位置查找指定字符在字符串中第一次出现处的索引,如果此字符串中没有这样的字符,则返回 -1。
  • int indexOf(String str)
  • int indexOf(String str, int fromIndex)

split

public String[] split(String regex, int limit)

  • regex -- 正则表达式分隔符。
  • limit -- 分割的份数。
1
str.split("-", 2)

Math

Math.max()

Math.pow(double m, double n)

m^n

Random

1
2
3
4
5
Random numList = new Random(); //默认当前系统时间的毫秒数为种子
//生成一个[50,100)之间的随机数
int num = numList.nextInt(50) + 50 ;
//生成[0,1.0)区间的小数
double d1 = numList.nextDouble()

Java_note
http://example.com/2024/10/11/Java-note/
作者
LSL
发布于
2024年10月11日
许可协议