摘要:語法清單翻譯自的,從屬于筆者的入門與實踐系列。需要注意的是,此文在上也引起了廣泛的討論,此文講解的語法要點還是以為主,未涉及中內容,略顯陳舊,讀者可以帶著批判的視角去看。
Java CheatSheet 基礎 hello, world! : if-else: loops: do-while:Java 語法清單翻譯自 egek92 的 JavaCheatSheet,從屬于筆者的 Java 入門與實踐系列。時間倉促,筆者只是簡單翻譯了些標題與內容整理,支持原作者請前往原文點贊。需要注意的是,此文在 Reddit 上也引起了廣泛的討論,此文講解的語法要點還是以 Java 7 為主,未涉及 Java 8 中內容,略顯陳舊,讀者可以帶著批判的視角去看。
do { System.out.println("Count is: " + count); count++; } while (count < 11);switch-case: 數組: 二維數組: 對象: 類: 方法: Java IDE 比較:
yes I took this from Wikipedia
個人推薦 IntelliJ IDEA 并且對于 學生免費.
字符串操作 字符串比較:boolean result = str1.equals(str2); boolean result = str1.equalsIgnoreCase(str2);搜索與檢索:
int result = str1.indexOf(str2); int result = str1.indexOf(str2,5); String index = str1.substring(14);單字節處理:
for (int i=0;i字符串反轉: public class Main { public static void main(String[] args) { String str1 = "whatever string something"; StringBuffer str1buff = new StringBuffer(str1); String str1rev = str1buff.reverse().toString(); System.out.println(str1rev); } }按單詞的字符串反轉:public class Main { public static void main(String[] args) { String str1 = "reverse this string"; Stack大小寫轉化:String strUpper = str1.toUpperCase(); String strLower = str1.toLowerCase();首尾空格移除:String str1 = " asdfsdf "; str1.trim(); //asdfsdf空格移除:str1.replace(" ","");字符串轉化為數組:String str = "tim,kerry,timmy,camden"; String[] results = str.split(",");數據結構 重置數組大小:int[] myArray = new int[10]; int[] tmp = new int[myArray.length + 10]; System.arraycopy(myArray, 0, tmp, 0, myArray.length); myArray = tmp;集合遍歷:for (Iterator it = map.entrySet().iterator();it.hasNext();){ Map.Entry entry = (Map.Entry)it.next(); Object key = entry.getKey(); Object value = entry.getValue(); }創建映射集合:HashMap map = new HashMap(); map.put(key1,obj1); map.put(key2,obj2); map.put(key2,obj2);數組排序:int[] nums = {1,4,7,324,0,-4}; Arrays.sort(nums); System.out.println(Arrays.toString(nums));列表排序:List列表搜索:unsortList = new ArrayList (); unsortList.add("CCC"); unsortList.add("111"); unsortList.add("AAA"); Collections.sort(unsortList); int index = arrayList.indexOf(obj);finding an object by value in a hashmap:hashmap.containsValue(obj);finding an object by key in a hashmap:hashmap.containsKey(obj);二分搜索:int[] nums = new int[]{7,5,1,3,6,8,9,2}; Arrays.sort(nums); int index = Arrays.binarySearch(nums,6); System.out.println("6 is at index: "+ index);arrayList 轉化為 array:Object[] objects = arrayList.toArray();將 hashmap 轉化為 array:Object[] objects = hashmap.entrySet().toArray();時間與日期類型 打印時間與日期:Date todaysDate = new Date(); //todays date SimpleDateFormat formatter = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss"); //date format String formattedDate = formatter.format(todaysDate); System.out.println(formattedDate);將日期轉化為日歷:Date mDate = new Date(); Calendar mCal = Calendar.getInstance(); mCal.setTime(mDate);將 calendar 轉化為 date:Calendar mCal = Calendar.getInstance(); Date mDate = mDate.getTime();字符串解析為日期格式:public void StringtoDate(String x) throws ParseException{ String date = "March 20, 1992 or 3:30:32pm"; DateFormat df = DateFormat.getDateInstance(); Date newDate = df.parse(date); }date arithmetic using date objects:Date date = new Date(); long time = date.getTime(); time += 5*24*60*60*1000; //may give a numeric overflow error on IntelliJ IDEA Date futureDate = new Date(time); System.out.println(futureDate);date arithmetic using calendar objects:Calendar today = Calendar.getInstance(); today.add(Calendar.DATE,5);difference between two dates:long diff = time1 - time2; diff = diff/(1000*60*60*24);comparing dates:boolean result = date1.equals(date2);getting details from calendar:Calendar cal = Calendar.getInstance(); cal.get(Calendar.MONTH); cal.get(Calendar.YEAR); cal.get(Calendar.DAY_OF_YEAR); cal.get(Calendar.WEEK_OF_YEAR); cal.get(Calendar.DAY_OF_MONTH); cal.get(Calendar.DAY_OF_WEEK_IN_MONTH); cal.get(Calendar.DAY_OF_MONTH); cal.get(Calendar.HOUR_OF_DAY);calculating the elapsed time:long startTime = System.currentTimeMillis(); //times flies by.. long finishTime = System.currentTimeMillis(); long timeElapsed = startTime-finishTime; System.out.println(timeElapsed);正則表達式 使用 REGEX 尋找匹配字符串:String pattern = "[TJ]im"; Pattern regPat = Pattern.compile(pattern,Pattern.CASE_INSENSITIVE); String text = "This is Jim and that"s Tim"; Matcher matcher = regPat.matcher(text); if (matcher.find()){ String matchedText = matcher.group(); System.out.println(matchedText); }替換匹配字符串:String pattern = "[TJ]im"; Pattern regPat = Pattern.compile(pattern,Pattern.CASE_INSENSITIVE); String text = "This is jim and that"s Tim"; Matcher matcher = regPat.matcher(text); String text2 = matcher.replaceAll("Tom"); System.out.println(text2);使用 StringBuffer 替換匹配字符串:Pattern p = Pattern.compile("My"); Matcher m = p.matcher("My dad and My mom"); StringBuffer sb = new StringBuffer(); boolean found = m.find(); while(found){ m.appendReplacement(sb,"Our"); found = m.find(); } m.appendTail(sb); System.out.println(sb);打印所有匹配次數:String pattern = "sa(w)*t(w)*"; //contains "at" Pattern regPat = Pattern.compile(pattern); String text = "words something at atte afdgdatdsf hey"; Matcher matcher = regPat.matcher(text); while(matcher.find()){ String matched = matcher.group(); System.out.println(matched); }打印包含固定模式的行:String pattern = "^a"; Pattern regPat = Pattern.compile(pattern); Matcher matcher = regPat.matcher(""); BufferedReader reader = new BufferedReader(new FileReader("file.txt")); String line; while ((line = reader.readLine())!= null){ matcher.reset(line); if (matcher.find()){ System.out.println(line); } }匹配新行:String pattern = "d$"; //any single digit String text = "line one line two line three "; Pattern regPat = Pattern.compile(pattern, Pattern.MULTILINE); Matcher matcher = regPat.matcher(text); while (matcher.find()){ System.out.println(matcher.group()); }regex:beginning of a string: ^
end of a string: $
0 or 1 times: ?
0 or more times: (*) //without brackets
1 or more times: +
alternative characters: [...]
alternative patterns: |
any character: .
a digit: d
a non-digit: D
whitespace: s
non-whitespace: S
word character: w
non word character: W
數字與數學操作處理 built-in types:byte: 8bits, Byte
short: 16bits, Short
long: 64bits, Long
float: 32bits, Float
判斷字符串是否為有效數字:String str = "dsfdfsd54353%%%"; try{ int result = Integer.parseInt(str); } catch (NumberFormatException e){ System.out.println("not valid"); }比較 Double:Double a = 4.5; Double b= 4.5; boolean result = a.equals(b); if (result) System.out.println("equal");rounding:double doubleVal = 43.234234200000000234040324; float floatVal = 2.98f; long longResult = Math.round(doubleVal); int intResult = Math.round(floatVal); System.out.println(longResult + " and " + intResult); // 43 and 3格式化數字:double value = 2343.8798; NumberFormat numberFormatter; String formattedValue; numberFormatter = NumberFormat.getNumberInstance(); formattedValue = numberFormatter.format(value); System.out.format("%s%n",formattedValue); //2.343,88格式化貨幣:double currency = 234546457.99; NumberFormat currencyFormatter; String formattedCurrency; currencyFormatter = NumberFormat.getCurrencyInstance(); formattedCurrency = currencyFormatter.format(currency); System.out.format("%s%n",formattedCurrency); // $ 234.546.457,99二進制、八進制、十六進制轉換:int val = 25; String binaryStr = Integer.toBinaryString(val); String octalStr = Integer.toOctalString(val); String hexStr = Integer.toHexString(val);隨機數生成:double rn = Math.random(); int rint = (int) (Math.random()*10); // random int between 0-10 System.out.println(rn); System.out.println(rint);計算三角函數:double cos = Math.cos(45); double sin = Math.sin(45); double tan = Math.tan(45);計算對數double logVal = Math.log(125.5);Math library: 輸入輸出操作: 從輸入流讀取://throw IOexception first BufferedReader inStream = new BufferedReader(new InputStreamReader(System.in)); String inline =""; while (!(inline.equalsIgnoreCase("quit"))){ System.out.println("prompt> "); inline=inStream.readLine(); }格式化輸出:StringBuffer buffer = new StringBuffer(); Formatter formatter = new Formatter(buffer, Locale.US); formatter.format("PI: "+Math.PI); System.out.println(buffer.toString());formatter format calls: 打開文件:BufferedReader br = new BufferedReader(new FileReader(textFile.txt)); //for reading BufferedWriter bw = new BufferedWriter(new FileWriter(textFile.txt)); //for writing讀取二進制數據:InputStream is = new FileInputStream(fileName);int offset = 0; int bytesRead = is.read(bytes, ofset, bytes.length-offset);文件隨機訪問:File file = new File(something.bin); RandomAccessFile raf = new RandomAccessFile(file,"rw"); raf.seek(file.length());讀取 Jar/zip/rar 文件:ZipFile file =new ZipFile(filename); Enumeration entries = file.entries(); while(entries.hasMoreElements()){ ZipEntry entry = (ZipEntry) entries.nextElement(); if (entry.isDirectory()){ //do something } else{ //do something } } file.close();文件與目錄 創建文件:File f = new File("textFile.txt"); boolean result = f.createNewFile();文件重命名:File f = new File("textFile.txt");File newf = new File("newTextFile.txt"); boolean result = f.renameto(newf);刪除文件:File f = new File("somefile.txt"); f.delete();改變文件屬性:File f = new File("somefile.txt"); f.setReadOnly(); // making the file read only f.setLastModified(desired time);獲取文件大小:File f = new File("somefile.txt");long length = file.length();判斷文件是否存在:File f = new File("somefile.txt"); boolean status = f.exists();移動文件:File f = new File("somefile.txt"); File dir = new File("directoryName"); boolean success = f.renameTo(new File(dir, file.getName()));獲取絕對路徑:File f = new File("somefile.txt"); File absPath = f.getAbsoluteFile();判斷是文件還是目錄:File f = new File("somefile.txt"); boolean isDirectory = f.isDirectory(); System.out.println(isDirectory); //false列舉目錄下文件:File directory = new File("users/ege"); String[] result = directory.list();創建目錄:boolean result = new File("users/ege").mkdir();網絡客戶端 服務器連接:String serverName = "www.egek.us"; Socket socket = new Socket(serverName, 80); System.out.println(socket);網絡異常處理:try { Socket sock = new Socket(server_name, tcp_port); System.out.println("Connected to " + server_name); sock.close( ); } catch (UnknownHostException e) { System.err.println(server_name + " Unknown host"); return; } catch (NoRouteToHostException e) { System.err.println(server_name + " Unreachable" ); return; } catch (ConnectException e) { System.err.println(server_name + " connect refused"); return; } catch (java.io.IOException e) { System.err.println(server_name + " " + e.getMessage( )); return; }包與文檔 創建包:package com.ege.example;使用 JavaDoc 注釋某個類:javadoc -d homehtml -sourcepath homesrc -subpackages java.netJar 打包:jar cf project.jar *.class運行 Jar:java -jar something.jar排序算法Bubble Sort
Linear Search
Binary Search
Selection Sort
Insertion Sort
Over here
文章版權歸作者所有,未經允許請勿轉載,若此文章存在違規行為,您可以聯系管理員刪除。
轉載請注明本文地址:http://specialneedsforspecialkids.com/yun/66772.html
摘要:使用文件與以下好處安全。包作為內嵌在平臺內部處理的標準,能夠在各種平臺上直接使用命令詳解創建文件該命令沒有顯示壓縮過程,執行結果是將當前路徑下的路徑下的全部內容生成一個文件。使用如下命令即可將清單文件中的對提取到文件中。 JAR,Java Archive File,Java檔案文件。JAR文件是一種壓縮文件,與ZIP壓縮文件兼容,通常稱為JAR包。JAR文件中默認包含了一個名為META...
摘要:雅虎從很早就開始招聘和培養研究型人才,雅虎研究院就是在這個過程中應運而生的。今天我就來說一說雅虎研究院的歷史,以及過去十多年間取得的成就,聊一聊如何通過引進高級人才,迅速構建起一支世界級的研發團隊。 showImg(https://segmentfault.com/img/remote/1460000013995512); 作者:王下邀月熊 編輯:徐川 前端每周清單專注大前端領域內容,...
摘要:是完全的面向對象語言,它們通過類的形式組織函數和變量,使之不能脫離對象存在。而在基于原型的面向對象方式中,對象則是依靠構造器利用原型構造出來的。 JavaScript 函數式腳本語言特性以及其看似隨意的編寫風格,導致長期以來人們對這一門語言的誤解,即認為 JavaScript 不是一門面向對象的語言,或者只是部分具備一些面向對象的特征。本文將回歸面向對象本意,從對語言感悟的角度闡述為什...
閱讀 2100·2021-11-11 16:55
閱讀 3171·2021-10-11 10:58
閱讀 3038·2021-09-13 10:28
閱讀 3967·2021-07-26 23:57
閱讀 1005·2019-08-30 15:56
閱讀 1331·2019-08-29 13:15
閱讀 1258·2019-08-26 18:18
閱讀 1267·2019-08-26 13:44