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

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

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

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
    推荐阅读
  • 手机更新后打字键盘怎么没了(手机突然没有打字键盘了)

    今天,我的手机突然没有打字键盘了,急坏了!打开百度搜索下,其中有一个办法最简单:重启手机。我马上重启手机,打字键盘又恢复了!

  • 只有香如故的前一句(有全诗词介绍吗)

    只有香如故的前一句:零落成泥碾作尘,我来为大家科普一下关于只有香如故的前一句?零落成泥碾作尘,只有香如故。梅花如此清幽绝俗,出于众花之上,可是如今竟开在郊野的驿站外面,破败不堪的“断桥”,自然是人迹罕至、寂寥荒寒、梅花也就倍受冷落了。

  • 关于端午节的一句话(关于端午节的句子大全)

    关于端午节的一句话愿君开怀,幸福如意!南方的端午节要比北方的更有意思,气氛更浓郁,更能表现端午节特色。我的大领导,端午佳节到了,祝愿您,万事如意,四季平安,年年有余,心想事成,身体健康。月五,是端午,粽子香,龙舟舞。月五是端午,粽叶飘香鼻尖传。年年岁岁端午节,分分秒秒幸福时。

  • 国庆周记怎么写(国庆周记范文)

    国庆周记怎么写今天是十月一日,一年一度的国庆节又到了。国庆节放七天长假,有的人外出旅游去了,有的人在家里休息,有的人则还在一片书林中,难以走出来。到处呈现出节日里热闹的气氛。每次我过生日的时候,爸爸、妈妈都祝愿我能健康、快乐的成长。今天是祖国母亲的生日,我祝愿祖国繁荣昌盛,越来越强大。我还要提醒大家:过节日的时候人多车也多,过马路的时候一定要注意安全,而且还要做到红灯停,绿灯行。

  • 怎样挑榴莲(挑榴莲的方法)

    用指甲轻轻按一下,有痕说明比较新鲜,但如果果柄,小且干燥,说明榴莲存放已久,不是很新鲜了。如果榴莲有裂口,可以从裂口处闻一下,是否有非常的浓郁香甜。如果味道偏淡,说明不够成熟,不成熟的榴莲有一股青草味,如果香气浓郁,说明这个榴莲非常的饱满成熟。如果刺是很生硬的,刺和刺的距离比较宽,说明这个榴莲不是太成熟,肉也不是很多。

  • 活虾怎么保存到晚上(处理干净的虾怎么保存)

    2、切碎冷冻法:虾类的保鲜需要把虾处理干净后,放进不锈钢的盆子里,放上水,然后再放进冰箱,这些虾冻成冰块后,再把其打碎,然后再装到其保鲜袋里,再放进冰箱里,再次冷冻起来。

  • usb4规范详解(USB4正式发布传输速度可达40Gbps)

    USB4可支持同步数据显示协议,我们在USB2.0和3.0时代,在进行数据传输的时候可能会发生卡顿,比如我们用手机数据线投屏一部手机中的4K电影,也许在USB2.0的协议中可能无法完成,但是USB3.0协议中可能会发生卡顿等问题。USB4的出现将成为新的标准,原来越多的手机或者电脑将会搭载USB4接口。USB4的零售产品将会在2020年底上市,USB4的命名与上几代产品的命名规则可能会有所不同,USB4的命名大胆简洁,不会出现像USB3.0、USB3.1、USB3.X的命名方式,而是统一使用USB4标准。

  • 高尔夫r旅行版引进国内了吗 高尔夫r旅行版还会销售吗

    r旅行版高尔夫已经引入国内,但是这款车在国内限量销售,国内不到100台。高尔夫r是进口大众旗下的车型,高尔夫r是小钢炮车型。这款发动机配备了缸内直喷技术,采用铝合金气缸盖和铸铁气缸体。与这台发动机匹配的是一台7速双离合变速箱。R高尔夫的前悬挂采用麦弗逊式独立悬挂,后悬挂采用多连杆式独立悬挂。高尔夫配备全时四驱系统和多片式离合器中央差速器。

  • 60岁以上老人血糖20几了算高吗(正常血糖是多少)

    也就是说18岁以上的成年人当中,平均每两个人就有一个人可能是糖尿病。遵医嘱服药对于糖尿病患者来说,一般需要服用一些药物来控制体内的血糖,情况下可能需要注射胰岛素,所以糖尿病患者一定要谨遵医嘱服用药物,不要擅自停药,更不要自己更改治疗的方法,避免影响降糖的效果。

  • 日本驻华大使:感谢中方援助(日本驻中国大使)

    日本驻华大使垂秀夫在致辞中特意向中方的对日灾后援助活动表示感谢,他说,日本人民收到了中国政府和中国国民温暖的援助,并由此获得勇气。“3·11东日本大地震”发生后,中国政府第一时间提供紧急救助物资并派出救援力量,中国国际救援队是到达重灾区大船渡市的第一支国际救援队。垂秀夫称,来自中国的大量援助给日中两国国民感情带来积极影响。在当日活动上,中日出席嘉宾集体默哀,并依次向逝者献花。