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(); System.out.println(nu); float fl = cin.nextFloat(); double dou = cin.nextDouble(); char change = cin.next().charAt(0 ); String str = cin.next(); String st = cin.nextLine(); 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) { Scanner sc = new Scanner (System.in); int n = sc.nextInt(); sc.nextLine(); int [] nums = new int [n]; String[] input = sc.nextLine().split("," ); for (int i = 0 ; i < n; i++) { nums[i] = Integer.parseInt(input[i]); } 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) { double f = 111231.5585 ; System.out.println(String.format("%.2f" , f)); double f = 111231.5585 ; DecimalFormat df = new DecimalFormat ("#.00" ); System.out.println(df.format(f)); } }
快速输入输出
BufferedReader/Writer
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(); int c = cin.read(); int x = cin.read(); String d = cin.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 ); map.getOrDefault(Object key, V 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); } map.forEach((key, value) -> { System.out.println("Key: " + key + ", Value: " + 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);
add()/offer()
peek()
remove()/poll()
contains()
size()
toArray()
比较器
1 2 3 4 5 6 7 8 9 10 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 -- 分割的份数。
Math
Math.max()
Math.pow(double m, double n)
m^n
Random
1 2 3 4 5 Random numList = new Random (); int num = numList.nextInt(50 ) + 50 ;double d1 = numList.nextDouble()