高考考试网
当前位置: 首页 高考资讯

java基础语法总结(Java语法清单这次带来一点基础的学习套路)

时间:2023-07-29 作者: 小编 阅读量: 6 栏目名: 高考资讯

JavaCheatSheet基础hello,world!

Java CheatSheet

基础

hello, world! :

if-else:

loops:

do-while:

do {

System.out.println("Count is: "count);

count;

} while (count < 11);

switch-case:

数组:

二维数组:

对象:

类:

方法:

Java IDE 比较:

图片来自 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 stack = new Stack<>();

StringTokenizer strTok = new StringTokenizer(str1);

while(strTok.hasMoreTokens()){

stack.push(strTok.nextElement());

}

StringBuffer str1rev = new StringBuffer();

while(!stack.empty()){

str1rev.append(stack.pop());

str1rev.append(" ");

}

System.out.println(str1rev);

}

}

大小写转化:

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.length10];

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\n line two\n line three\n";

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

数字与数学操作处理

内建数据类型:

  • 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 \home\html

-sourcepath \home\src

-subpackages java.net

Jar 打包:

jar cf project.jar *.class

运行 Jar:

java -jar something.jar

排序算法

  • Bubble Sort
  • Linear Search
  • Binary Search
  • Selection Sort
  • Insertion Sort

Over here

  • Java
    推荐阅读
  • 公司注销需如何操作(公司注销怎么走简易流程)

    公司注册之后,如果不打算继续经营,那就需要按规定进行注销。其次,简易注销需要签署《全体投资人承诺书》,并且要对所提交材料的真实性、合法性负责。对于存在对外负债的公司来说,若进行简易注销,相当于全体投资人承诺对公司的债务承担相应的法律责任。并不是所有公司都适用于简易注销,因此企业主对于债务及税务问题需心中有数。

  • 鼠尾草和薰衣草的区别主要有哪些(鼠尾草和薰衣草的区别主要有哪些品种)

    鼠尾草和薰衣草的习性、形态、气味和价值各不相同。鼠尾草喜欢在温暖和阳光充足的环境中生长,最多可生长60厘米,其植物气味十分辛辣。不同习性许多人不知道鼠尾草和薰衣草的区别,事实上,他们的习性是不同的,鼠尾草喜欢在温暖、光线充足、通风良好的环境中生长,耐旱但不耐涝。不同气味大多数鼠尾草生长在海拔750米的草坡、河流或灌木丛中,其植物闻起来既辛辣又难闻。

  • 熟牛头肉太腥要怎么做(熟牛头肉怎么做好吃)

    热锅凉油,油烧到8成,下牛头肉翻炒出香味后,加香料、姜翻炒。沿着锅边淋入适量高度白酒或者料酒翻炒均匀出酒香味,再放陈醋去腥提味儿。放盐翻炒均匀,继续烧20分钟,等土豆易夹碎即可。加适量鸡精翻炒均匀调味,起锅装盘,撒上香菜段即可。

  • 王健林及万达集团在汶川地震灾区的巨额捐助(王健林及万达集团在汶川地震灾区的巨额捐助)

    王健林及万达集团在汶川地震灾区的巨额捐助今年5月12日,四川省汶川县映秀镇举行了“5·12”汶川特大地震抗震救灾十周年纪念仪式。5月13日上午,万达集团通过四川省慈善总会向四川地震灾区捐款的500万元,成为四川省收到的第一笔巨额现金捐助。地震过后,人们急于购买水、粮等物资,但大多商店卖场暂停营业。营业当天,商场停车场的车辆数甚至创下了新高。

  • 刘畅个人资料简介(有关刘畅的介绍)

    刘畅个人资料简介刘畅,1986年10月10日出生于江苏省东台市,中国内地男演员、模特,高中就读于三仓中学,大学毕业于金陵科技学院。2012年初,首次出席秋冬伦敦时装周。2016年,出演科幻动作电影《逆时营救》。2017年,出演网剧《疯人院》,在剧中饰演医生孟喃;10月,主演的院线电影《那一场呼啸而过的青春》上映。

  • 豌豆怎么保鲜小窍门(如何保存豌豆)

    下面更多详细答案一起来看看吧!豌豆怎么保鲜小窍门用保鲜袋装好新鲜豌豆粒,直接进入冰箱冻室冷冻。将豌豆在开水中焯水3~5分钟,捞起凉冷,装入保鲜袋,放进冰箱冷冻室冷冻。这个方法比第一个方法保存时间久。豌豆可以之间晾干,然后密封存储。干的豌豆可以磨成豌豆面再加工食用。

  • oppoa11手机是5g手机吗(5000mAh骁龙665线下销量之王OPPO)

    提到OPPO手机,大家的第一印象是什么呢?说实话,小编人生中第一款正式的手机就是OPPOR15。可以说R系列虽然处理器不是旗舰,不过在其他方面,OPPO的做工和配置都是很高的。我们今天要说的就是OPPOA11这款手机。整体来说颜值这方面OPPO一直做的还不错。总的来说,作为OPPO的入门级系列,假如把售价放在1000元价位以下,还是有一定竞争力的,放在竞争如此激烈的千元机市场,虽然在线下销量还不错,不过长时间了,也会是受到吐槽声一片的。

  • 多久敷一次面膜才是最好的(每天早晚都敷面膜好吗)

    建议10至15分钟,以免精华液全乾后,肌肤反而更缺水。所以最佳的敷面膜时间应为洗澡后半小时之内。可是,不推荐将睡眠面膜作为日霜使用,因为其油脂及滋润度比日霜高及浓,所以在白天敷睡眠面膜容易有泛油光的困扰。太常使用面膜反而有可能造成肌肤负担或敏感。

  • 欢乐颂演员名单包奕凡(吻你之时别再躲)

    不少网友看了欢乐颂之后纷纷被里面的歌曲给圈粉了。5月15日,网易云音乐独家上线“小包总”包奕凡人物主题曲《吻你之时别再躲》,演员杨烁深情演绎,苏到炸裂。开始近似独白的“手别再颤抖/别再梦游/别再让泪随风掉落/别躲在堡垒的尽头”在“小包总”浑厚的音色中,展现出一缕对爱人的心疼。

  • 正规税务发票鉴别(辨别真假发票的6个方法)

    正规税务发票鉴别国家税务总局发布的《关于调整增值税普通发票防伪措施有关事项的公告》,决定调整增值税普通发票防伪措施,自2016年第四季度起印制的增值税普通发票采用新的防伪措施。小编为大家整理了以下6个方法:一、白纸鉴别法增值税普通发票的新防伪措施为灰变红防伪油墨。目前,假票无法做到这一点。六、微信查验部分省市的国税系统已入驻微信“城市服务”平台。