JAVA常用STL

輸入與輸出

1.輸入

  • 基本輸入
Scanner sc=new Scanner(System.in);
Scanner in = new Scanner (new BufferedInputStream(System.in));//更快
  • 輸入格式
1. 只有一組數據:

    Scanner sc=new Scanner(System.in);
    int a=s.nextInt();
    int b=s.nextInt();

2. 輸入多組數據,不告知組數,也沒有截止符

    Scanner sc=new Scanner(System.in);
    while(sc.hasNext()){//判斷是否數據結束
        int a=s.nextInt();
        int b=s.nextInt();
    }

3. 輸入多組數據,不告知組數,截止符爲ch

	Scanner sc=new Scanner(System.in);
	while(sc.hasNext()){
		int c=sc.nextInt();
		if(c==ch) return;
	}

4. 輸入多組數據,第一行是整數N,表示有N組數據,之後每行表示一組數據

  
    int n;
    Scanner sc=new Scanner(System.in);
    n=sc.nextInt();
    for(int i=0;i<n;i++){
       int a=sc.nextInt();
       int b=sc.nextInt();
    }

5.養成良好習慣,最後關閉輸入流
	
	sc.close();
  • 輸入掛(當輸入規模達到106的時候,就需要輸入掛,否則很有可能超時)
import java.io.*;
import java.util.*;
import java.math.*;
 
public class Main
{
 
    public static void main(String[] args)
    {
        InputReader in = new InputReader();
        PrintWriter out = new PrintWriter(System.out);
        out.close();
    }
}
class InputReader
{
    BufferedReader buf;
    StringTokenizer tok;
    InputReader()
    {
        buf = new BufferedReader(new InputStreamReader(System.in));
    }
    boolean hasNext()
    {
        while(tok == null || !tok.hasMoreElements()) 
        {
            try
            {
                tok = new StringTokenizer(buf.readLine());
            } 
            catch(Exception e) 
            {
                return false;
            }
        }
        return true;
    }
    String next()
    {
        if(hasNext()) return tok.nextToken();
        return null;
    }
    int nextInt()
    {
        return Integer.parseInt(next());
    }
    long nextLong()
    {
        return Long.parseLong(next());
    }
    double nextDouble()
    {
        return Double.parseDouble(next());
    }
    BigInteger nextBigInteger()
    {
        return new BigInteger(next());
    }
    BigDecimal nextBigDecimal()
    {
        return new BigDecimal(next());
    }
}

2.輸出

PrintWriter out = new PrintWriter(new BufferedOutputStream(System.out));//使用緩存加速,比直接使用System.out快
out.print(n)//不換行
out.println(n); //自動換行
out.printf("%.2f\n", ans); // 與c語言中printf用法相同

3.文件讀寫

	try {
			FileInputStream fip = new FileInputStream("D:\\java\\maze.txt"); // str1爲讀取的文件路徑
			BufferedReader bfr = new BufferedReader(new InputStreamReader(fip));
			 // 如果單純的使用fip.read()一個字節一個字節的讀取,則比較耗費時間,
			 //採用BufferedReader則可以一行行的讀取
		} catch (IOException e) {
			e.printStackTrace();
		}

		File file = new File(str);
		try {
			FileOutputStream fop = new FileOutputStream(file); // 創建輸出流對象
			String s = "hello,word!";
			byte[] b = new byte[1024];
			b = s.getBytes(); // 將String類型的s字符串以字符的形式賦給字節數組
			try {
				fop.write(b, 0, b.length);
				fop.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}

大整數與高精度

1.大整數BigInteger

    import java.math.BigInteger; 
    //主要有以下方法可以使用: 
    BigInteger add(BigInteger other) //加
    BigInteger subtract(BigInteger other)//減 
    BigInteger multiply(BigInteger other) //乘
    BigInteger divide(BigInteger other)//除
    BigInteger [] dividedandRemainder(BigInteger other) //取餘,數組第一位是商,第二位是餘數
    BigInteger pow(int other)//冪
    BigInteger mod(BigInteger other) //模
    BigInteger gcd(BigInteger other) //公約數
    int compareTo(BigInteger other) //比較,小於返回負,等於返回0,大於返回正
    static BigInteger valueOf(long x)//轉型
    //輸出數字時直接使用 System.out.println(a) 即可

2.高精度BigDecimal

BigDecimal add(BigDecimal other)//加
BigDecimal subtract(BigDecimal other)//減
BigDecimal multiply(BigDecimal other)//乘
BigInteger divide(BigInteger other)//除
//除數,保留小數位數,保留方法四捨五入
BigDecimal divide(BigDecimal divisor, int scale, BigDecimal.ROUND_HALF_UP)
 //用於格式化小數點,setScale(1)表示保留一位小數,默認四捨五入
BigDecimal.setScale()

字符串與進制轉換

1.字符串基本操作

String s = "abcdefg";
char [] ch;
ch = s.toCharArray(); // 字符串轉換爲字符數組.
for (int i = 0; i < ch.length; i++){
    ch[i] += 1; //字符數組可以像C++ 一樣操作
}
System.out.println(ch); // 輸出爲“bcdefgh”.

2.進制轉換

		int num=150;
		int Bnum=0b11;//二進制 3
		int Onum=017;//八進制 15
		int Hnum=0x1A;//十六進制 26
		String numB=Integer.toBinaryString(num);//二進制 10010110
		String numO=Integer.toOctalString(num);//八進制 226
		String numH=Integer.toHexString(num);//十六進制 96

數據結構

1.set

在Java中主要使用HashSet類進行去重,HashSet中元素是無序的(可以理解爲順序不確定),LinkedHashSet是遍歷時是按照插入順序排序的,TreeSet是升序排列的,最接近C++中的set,但是在沒有要求元素有序的情況下,Java中一般是使用HashSet的。下節的map的情況與之類似。

Set<Integer> set = new HashSet<Integer>();//無序,對應標準C++的unordered_set
set.add(1);//添加元素
System.out.println(s.contains(1));//查詢
set.remove(1);//刪除元素

如果使用有序的TreeSet,還可以進行如下的查找操作:

TreeSet<Integer> s = new TreeSet<Integer>();
//使用s.add(1);等把1-5都加進去,代碼省略
System.out.println(s.ceiling(3));   //>=3的最小的數,輸出3
System.out.println(s.floor(3));     //<=3的最大的數,輸出3
System.out.println(s.higher(3));    //>3的最小的數,輸出4
System.out.println(s.lower(3));     //<3的最大的數,輸出2
System.out.println(s.headSet(3));   //<3的數組成的TreeSet,輸出[1, 2]
System.out.println(s.tailSet(3));   //>=3的數組成的TreeSet,輸出[3, 4, 5]
System.out.println(s.subSet(2,4));  //>=2且<4的數組成的TreeSet,輸出[2, 3]
System.out.println(s.subSet(2,false,4,true));   //>2且<=4的數組成的TreeSet,輸出[3, 4]

2.map

如果只需要C++中map的key對value的映射功能,而不關心順序,Java中一般使用HashMap類,如需有序,與Set類似,有LinkedHashMap、TreeMap等類可以使用。
例子如下:

//定義與存取
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
map.put(1, 111);
System.out.println(m.get(1));//如果get一個不存在的key,則返回null,否則返回對應value
//用迭代器遍歷
Iterator<Entry<Integer, Integer>> it = map.entrySet().iterator();
while(it.hasNext()){
   Entry<Integer, Integer> e = it.next();
   System.out.println(e.getKey() + " " + e.getValue());
}
//根據key刪除元素
map.remove(1);
//用for-each循環遍歷
for(Map.Entry<Integer, Integer> e:map.entrySet()){
   System.out.println(e.getKey() + " " + e.getValue());
}

3.vector(list)

在Java中,C++的vector對應的是ArrayList類,list對應LinkedList類,其基本用法跟ArrayList類似,只是實現上使用鏈表而不是數組,從而在一些操作的複雜度上有變化,將下文代碼的ArrayList改爲LinkedList可直接使用,故在此省略。(其實它還實現了C++中queue、deque、stack等的功能,有使用鏈表實現的這些數據結構的需求的話可以用它)雖然Java中也有Vector這個類,但它是歷史遺留下來的,不建議使用。

ArrayList<Integer> a = new ArrayList<Integer>();//創建一個儲存整形的ArrayList
a.add(1);   //向其最後添加“1”這個元素
a.add(2);   //向其最後添加“2”這個元素
a.add(1, 3);    //向其index爲1的位置添加“3”這個元素,原來index爲1及後續元素向後順延一位;index以0起始
a.remove(1);    //刪除index爲1的元素,注意不是刪除值爲1的元素
a.remove(Integer.valueOf(1));   //刪除值爲1的元素
a.set(0, 1);    //將index爲0的元素的值改成1
System.out.println(a.get(0));   //取出index爲0的元素並輸出,結果爲1

4.priority_queue

在Java中,C++的priority_queue對應的是PriorityQueue類。示例如下:

PriorityQueue<Integer> pq = new PriorityQueue<Integer>();//定義一個儲存整形的優先隊列,值小的在前
pq.offer(1);//將1添加進去,不能用add(),雖然能過編譯!!!
pq.offer(3);
pq.offer(2);
//跟C++的不同,你可以遍歷它,但是你會發現遍歷的結果並不是有序……此處輸出1 3 2 
for(int num:pq){
    System.out.print(num + " ");
}
System.out.println(pq.peek());//取出第一個值但不刪除它
System.out.println(pq.poll());//取出第一個值並且刪除它
System.out.println(pq);//輸出剩下的元素,結果是[2, 3],但是並不是排序之後的!!!這只是巧合,不信試試其他值

5.queue

C++中的queue在Java中可以使用ArrayDeque類,實例如下:

    ArrayDeque<Integer> queue = new ArrayDeque<Integer>();
    queue.offer(1);//成功返回true,失敗返回false,不要寫成push,實現棧時使用
    queue.offer(2);
    queue.offer(3);
    System.out.println(queue.peek());//取出第一個值但不刪除它
    while (!queue.isEmpty()) {
        System.out.println(queue.pop());//取出第一個值並且刪除它
    }

6.stack

C++中的stack在Java中使用ArrayDeque類。Java也有Stack類,但也是歷史遺留問題。語法基本相同,示例如下:

ArrayDeque<Integer> stack = new ArrayDeque<Integer>();
stack.push(1);//此處採用push
stack.push(2);
stack.push(3);
System.out.println(stack.peek());//查看棧頂元素
while(!stack.isEmpty()){
    System.out.println(stack.pop());//彈出棧頂元素
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章