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

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

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

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
    推荐阅读
  • 怀化市属于哪个省(怀化市是哪个省)

    怀化市属于哪个省怀化市,别称“鹤城”,古称“鹤州”、“五溪”,湖南省地级市,位于湖南省西部偏南,处于武陵山脉和雪峰山脉之间,地处北纬25°52′22″~29°01′25″,东经108°47′13″~111°06′30″之间,总面积27564平方千米。怀化市地处中亚热带川鄂湘黔气候区和江南气候区的过渡部位,境内四季分明,严寒酷暑期短。截至2021年1月,怀化市辖1个市辖区、10个县,代管1个县级市,另辖1个管理区,市政府驻鹤城区。

  • 为什么要远离垃圾食品(关于为什么要远离垃圾食品介绍)

    为什么要远离垃圾食品垃圾食品可以解释为高糖、高油、高盐又焦糊的食品,这些食品里面含有的糖和油等都超出了人体需要,从而变成了人体不需要的多余的食品,并且长期吃这些超出人体需要的高油糖等的食品,对人体会造成很大的危害。一般人们也将大部分对人体健康没有帮助的食品也视作为垃圾食品。现在越来越多的家长重视到孩子的健康问题,时刻谨记孩子不要吃垃圾食品,要远离垃圾食品。

  • 第四代帝豪豪华型配置(买什么车比较划算呢)

    第四代帝豪豪华型配置二叔家的孩子大学毕业,在县城里上班有二年多了,手里积攒有七八万元,想买辆日常上班用的代步车。我脑海里立马浮现出第四代帝豪的影子,这车简直就是为他量身定做的。四代帝豪的车尾非常的性感,左右贯穿一体式尾灯,刹车时显得更加时髦,亮眼。四代帝豪轮胎规格是195/55,R16。

  • 王者荣耀最强王者该有的思路(如今的最强王者水平到底如何)

    但是情况却截然相反,绝悟AI模式虽然没有排位与巅峰赛那样高的功利性,但是一天只能挑战五次,而且还有时间限制,过了固定时间这个模式就会下架,所以对于一些一样拿到最终称号的玩家,还是有一定挑战性的。而绝悟AI模式中,如果总是匹配到这种滥竽充数的最强王者,很难通关,也就不难解释了。

  • 别克全新7座昂科雷(新款别克昂科雷)

    确实如此,这两款车几乎是目前30万元级别中最均衡7座SUV车型了,但这并不代表没有其他选择了。包括可以减轻长途驾驶疲惫感的自适应巡航、避免发生事故的主动刹车和车道保持等功能,与同级别车型配备不相上下。因为目前别克在5米以上的SUV市场中仍处于空白状态,而别克一向喜欢推出各种细分车型,所以外界猜测新款昂科雷将有可能国产来补充产品线的空缺。

  • 最好的一天歌词(最好的一天全部歌词)

    最好的一天歌词?下面更多详细答案一起来看看吧!

  • 男孩子爱哭怎么教育(男孩子爱哭如何教育)

    我们一起去了解并探讨一下这个问题吧!男孩子爱哭怎么教育对孩子的敏感要表示理解如果孩子因富有同情心而哭,家长首先需要理解孩子,站在孩子的角度来看待问题。同时要告诉孩子,你如果想帮助别人,“哭”是不能起到作用的,而是要通过动脑筋想办法来帮助别人,而哭解决不了任何问题。让孩子学会用正确的方式来表达情绪当孩子遇到了困难而哭的时候,家长要告诉孩子,只哭不说的话,爸爸妈妈不了解情况也不知道怎么帮你。

  • 西红柿和水果西红柿有什么不一样(番茄和西红柿有什么区别)

    西红柿富含一种叫作番茄红素的植物化合物,所以它是具有这个鲜红的颜色,能够帮助西红柿免受太阳和紫外线的伤害,那我们吃了它,也能够保护身体的细胞不受伤害。一些研究表明,西红柿可能会对哮喘患者有帮助有助于防止肺气肿;5、西红柿还能够保证血管的健康,保证血管的通畅性,防止血液的凝结,多吃西红柿可以降低患中风的几率。

  • 规律的特点(规律有哪些特点)

    规律的特点规律具有客观性。规律是客观存在的,是不以人们的意志为转移的,但人们能够通过实践认识它、利用它;规律具有重复性。这是其最基本的属性,人们正是对社会、自然现象的多次重复进行探索,抓住其内在联系,证明它的规律性;规律具有稳定性。规律虽然不是一成不变,但它具有相对稳定性。比如农历的24节气,几千年来虽然有些变化,特别昌近几年虽着地球变暧,节气略有提前,但总的规律没有大的变化。

  • 鸡血石产地 内蒙鸡血石产地

    鸡血石产地是浙江临安。鸡血石是辰砂条带的地开石,因鲜红色似鸡血的辰砂(朱砂)而得名。鸡血石含有辰砂(朱砂)、石英、玉髓35%-45%。磁铁矿、赤铁矿6%-12%。