Java的运行
Java编译过程不生成机器语言,生成字节码。同时具备高级语言的可移植性。(一次编写到处运行)
Java创建了JVM(Java虚拟机),通过JVM支持字节码的解释运行。
Java程序的构成
- 源代码文本文件:后缀为”.java”
- 文件名:首字母大写,必须为英文,不能有空格
-
变量
为了存储数据,我们会先创建变量 例:
String say;
-
方法
随机数 Math.random() //double型的数据
Math.random()方法用于返回一个随机数,范围为【0.0,1.0】
// 得到一个随机数double value = Math.random();System.out.println(value);
类型转化
int nValue =(int) value;
如果想得到0~9之间的随机数,需要×10
// (value*10) 用小括号包围是因为先乘10得到结果在转化为整数// 要不然得不到结果,这个就是数学的优先级int nValue = (int) (value*10);
生成6位随机数时,有时生成的是0.011233…,×1000000之后我们发现有时只有5位,
于是我们可以将生成的随机数+1或者进行一些其他的操作,让最终的结果变成6位。
public static void main(String[] args) {double value =Math.random();if(value<0.1){value=value+1;int code =(int)(value*100000);System.out.println(code);}else{int code =(int)(value*1000000);System.out.println(code);}
自定义方法
- main()方法
// public(公共的) static(静态) void(空类型)public static void 方法名称(方法参数){代码块}
方法名遵守小驼峰命名法
// 密码public static void password(){//代码块}// 我的文档public static void myDocument(){//代码块}
将上面的调用随机数方法写在自己定义的方法中,要用的时候直接调用random()就好了
public class Custom {public static void main(String[] args) {random();}/***生成6位随机数*/public static void random(){int code = (int) ((Math.random()+1) * 100000);System.out.println(code);}}
方法参数
短信验证码例子最终版
public class MessageCode1 {public static void code(int length,String text){int random=(int)((Math.random()*9+1)*length);System.out.print(text+"【"+random+"】");}public static void main(String args[]){String txt="你本次的验证码是";code(1000,txt);}}
for循环
String[] tables = new String[3];tables[0] = "张三";tables[1] = "李四";tables[2] = "王五";for(int i = 0; i< tables.length;i++){String name = tables[i];System.out.println(name);}
我们在数据确定的情况下也可以写成下面这样,这段代码同时完成了数组长度的设定和数组的赋值
public static void main(String[] args) {String[] tables = new String[]{"张三","李四", "王五"};for(int i = 0; i < tables.length; i++){String name = tables[i];System.out.println(i+":"+name);}}
另一种for循环
for(String name : tables){}//上面的循环和下面的是同一个意思for(int i = 0; i < tables.length; i++){String name = tables[i];}
字符串长度
String message = "今天我在学习 Java 字符串";int size = message.length();System.out.println(size);
验证消息长度封装为方法
public class Test71 {public static void main(String[] args) {boolean countPass = validateCount("今天天气挺好的");System.out.println(countPass);}public static boolean validateCount(String message){if(message.length()>140){return false;}return true;mess}}
取出字符串中的某个字
public static void main(String[] args) {String message = "Hello Java";// 取出第一个字char str = message.charAt(0);System.out.println(str);// 取出第二个字str = message.charAt(1);System.out.println(str);}
for循环得到每一个字符
public static void main(String[] args) {print("今天天气挺好的");}public static void print(String message){for (int i = 0; i < message.length(); i++) {char str = message.charAt(i);System.out.println(str);}}
去掉字符串左右多余的空格
使用trim()方法
String str = " 优课达 ";// 处理去空格String newStr = str.trim();}
字符串的常用方法(查找,拼接)
String str = "Java是一种广泛使用的计算机编程语言,拥有跨平台、面向对象、泛型编程的特性,广泛应用于企业级Web应用开发和移动应用开发。任职于太阳微系统的詹姆斯·高斯林等人于1990年代初开发Java语言的雏形,最初被命名为Oak,目标设置在家用电器等小型系统的编程语言,应用在电视机、电话、闹钟、烤面包机等家用电器的控制和通信。由于这些智能化家电的市场需求没有预期的高,Sun公司放弃了该项计划。随着1990年代互联网的发展,Sun公司看见Oak在互联网上应用的前景,于是改造了Oak,于1995年5月以Java的名称正式发布。Java伴随着互联网的迅猛发展而发展,逐渐成为重要的网络编程语言。";//查找: indexOf();int index = str.indexOf("Java");//查找第二次出现javaint index = str.indexOf("Java");index = str.indexOf("Java", index + 4);//拼接:substring();//打印出"java"之后的所有内容String newStr = str.substring(index+4);//打印出“java”之后的三个字节String newStr = str.substring(index+4,index+7);
判断字符串的“开始”或“结尾”
String fileName = "报告.doc";//判断结尾是否为“.doc”if(fileName.endsWith(".doc")){System.out.println("是word文档");}}
String url = "https://www.youkeda.com";//判断开头是否为“https”if(url.startsWith("https")){System.out.println("网址是安全的");}
字符串替换
replaceAll(“旧”,”新”);
String str = "Java是一种广泛使用的计算机编程语言,拥有跨平台、面向对象、泛型编程的特性,广泛应用于企业级Web应用开发和移动应用开发。于1995年5月以Java的名称正式发布。Java伴随着互联网的迅猛发展而发展,逐渐成为重要的网络编程语言。";String newStr = str.replaceAll("Java","Python");//替换为空值(删除)String name = fileName.replaceAll(".doc","");
字符串分割
split()
String text = "姓名|年龄|性别\n张三|20|男\n李四|18|男\n小花|18|女";// 使用 split 进行换行符的分隔,得到一个新的数组对象String[] data = text.split("\n");// 因为第一行是标题不是数据,所以我们需要把长度-1//(注意要使用小括号包围,因为要先计算长度再组合字符串)System.out.println("共有:" + (data.length - 1) + " 条记录");
String text = "姓名|年龄|性别\n张三|20|男\n李四|18|男\n小花|18|女";// 使用 split 进行换行符的分割,得到一个新的数组对象String[] data = text.split("\n");// 因为第一行是标题不是数据,所以我们需要把长度-1// (注意要使用小括号包围,因为要先计算长度再组合字符串)System.out.println("共有:"+(data.length-1)+" 条记录");// 忽略第一行标题数据,所以我们把 i 设为1,从第二条记录开始for(int i=1;i<data.length;i++){// 使用 \\| 进行字符串分割,得到一个新数组对象String[] lines = data[i].split("\\|");System.out.println("姓名:"+lines[0]+" 年纪:"+lines[1]+" 性别:"+lines[2]);}
特殊字符的分割
"."、"|"、"*"这三个字符作为分隔符时,需要加上“\\”作为转义符,eg:str.split("\\|");
大小写转换
转换为大写:toUpperCase();
转换为小写:toLowerCase();
public static void main(String[] args) {String text = "ZhanSan";// 把拼音全部转化为大写字母String enName = text.toUpperCase();System.out.println(enName);}
字符串比较 equals()
.equals()
String text = "字符串";// 使用 equals 方法判断是否相同if (text.equals("字符串")) {System.out.println("equals 方法字符串相等");}
数字和字符串转化
转化字符串为数字
String text = "123";// 转化字符串为数字int a = Integer.parseInt(text);System.out.println(a);// 转化字符串为数字a = Integer.parseInt("100");System.out.println(a);
转化数字为字符串
//与字符串拼接int a = 100;//使用空字符串相加数字,会自动变成字符串类型String str = ""+a;System.out.println(str);//String.valueOf()方法int a = 100;//使用valueOf强制把数字转化为字符串String str = String.valueOf(a);System.out.println(str);
java包管理
Java中导入包的语句是:
import 包名+类名
自定义时间格式
一定要记得执行日期的格式化处理,再打印出该字符串
import java.time.LocalDate;import java.time.format.DateTimeFormatter;public class DateTest5 {public static void main(String[] args) {//得到的默认日期格式yyyy-MM-ddLocalDate time = LocalDate.now();// 创建一个新的格式化方式DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy年MM月dd日");// 执行日期的格式化处理,得到期望格式的日期字符串String timeStr = df.format(time);}}
获取当前时间具体的值
import java.time.LocalDate;public class DateTest7 {public static void main(String[] args) {LocalDate time = LocalDate.now();// 得到当前时间所在年int year = time.getYear();System.out.println("当前年份 " + year);// 得到当前时间所在月int month = time.getMonth().getValue();System.out.println("当前月份 " + month);// 得到当前时间所在日int day = time.getDayOfMonth();System.out.println("当前日 " + day);// 得到当前时间所在星期数int dayOfWeek = time.getDayOfWeek().getValue();System.out.println("当前星期 " + dayOfWeek);}}
将字符串转化为日期
import java.time.LocalDate;public class DateTest8 {public static void main(String[] args) {// 定义一个时间字符串String date = "2019-01-01";// 把字符串转化位 LocalDate 对象,并得到字符串匹配的日期LocalDate date2 = LocalDate.parse(date);// 打印出日期System.out.println(date2.toString());}}
如果日期的格式不是yyyy-MM-dd就需要增加一句下面的额代码,进行格式的转换。
//()中的格式是当前传入字符串的格式DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy/MM/dd");
整体代码如下:
import java.time.LocalDate;import java.time.format.DateTimeFormatter;public class DateTest81 {public static void main(String[] args) {String date = "2019/01/01";DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy/MM/dd");// 把字符串转化位 LocalDate 对象,并得到字符串匹配的日期LocalDate date2 = LocalDate.parse(date,df);// 打印出日期System.out.println(date2.toString());}}
计算日期
import java.time.LocalDate;public class DateTest9 {public static void main(String[] args) {//5.1入住,住四天LocalDate leaveTime = getLeaveTime("2019-05-01", 4);System.out.println(leaveTime.toString());}public static LocalDate getLeaveTime(String checkInTime, int days) {// 把字符串转化为 LocalDate 类型LocalDate time = LocalDate.parse(checkInTime);// 使用 plusDays 添加天数,得到新的时间LocalDate leaveTime = time.plusDays(days);return leaveTime;}}
其他时间的计算
import java.time.LocalDate;public class DateTest10 {public static void main(String[] args) {LocalDate now = LocalDate.now();System.out.println("当前:" + now.toString());System.out.println("加法运算");System.out.println("加1天:" + now.plusDays(1));System.out.println("加1周:" + now.plusWeeks(1));System.out.println("加1月:" + now.plusMonths(1));System.out.println("加1年:" + now.plusYears(1));System.out.println("减法运算");System.out.println("减1天:" + now.minusDays(1));System.out.println("减1周:" + now.minusWeeks(1));System.out.println("减1月:" + now.minusMonths(1));System.out.println("减1年:" + now.minusYears(1));}}
两个日期的比较
import java.time.LocalDate;public class DateTest11 {public static void main(String[] args) {LocalDate now = LocalDate.now();// 可以对两个 LocalDateTime 进行比较,// 可以判断一个日期是否在另一个日期之前或之后,// 或者判断两个日期是否是同年同月同日。boolean isBefore = now.minusDays(1).isBefore(LocalDate.now());System.out.println("是否在当天之前:" + isBefore);boolean isAfter = now.plusDays(1).isAfter(LocalDate.now());System.out.println("是否在当天之后:" + isAfter);// 判断是否是当天boolean sameDate = now.isEqual(LocalDate.now());System.out.println("是否在当天:" + sameDate);}}
自定义类
com.youkeda.test.Hello.java 这样的Java类,我们的代码是这样的
package com.youkeda.test;public class Hello {}
我们多了一个package包路径这样的语法,这个就是包的声明,注意这个语法,包路径是该Java所在的包目录。-个文件只有一个package语句,并且一般是在文件第一行
有了包和自定义类之后,我们就可以把代码放在不同的类中。
package com.youkeda.test;import java.time.LocalDate;/*** 酒店工具类,用于计算入住和离店时间*/public class HotelTool {/*** 根据离店时间和入住天数得到入住时间** @param leaveTime* @param days* @return*/public static LocalDate getCheckInTime(String leaveTime, int days) {// 把字符串转化为 LocalDate 类型LocalDate time = LocalDate.parse(leaveTime);// 使用 minusDays 减少天数,得到新的时间LocalDate checkInTime = time.minusDays(days);return checkInTime;}/*** 根据入住时间和入住天数得到离店时间** @param checkInTime* @param days* @return*/public static LocalDate getLeaveTime(String checkInTime, int days) {// 把字符串转化为 LocalDate 类型LocalDate time = LocalDate.parse(checkInTime);// 使用 plusDays 添加天数,得到新的时间LocalDate leaveTime = time.plusDays(days);return leaveTime;}}/**我们可以通过导入包来任意调用你自定义的函数。*/package com.youkeda.test;import java.time.LocalDate;/*** 酒店预定类*/public class HotelOrder {public static void main(String[] args) {LocalDate checkIn = HotelTool.getCheckInTime("2019-01-03", 5);System.out.println(checkIn.toString());}}
注:在同一个包中的类可以省略下面这一句
import com.youkeda.test.HotelTool;
实例化对象
File myFile = new File("mywork.docx");
实例化对象之后,常用的方法
//得到文件名String fileName = myFile.getName();//实例化 File,传入一个文件路径,文件路径使用 / 作为分隔符File myFile = new File("mywork/201408 人物角色.docx");String fileName = myFile.getName();//得到文件的完整路径(包含文件名)String getAbsolutePath()//得到文件路径(不包含文件名)String getPath()//判断文件是否存在boolean exists()File myFile = new File("mywork/201408 人物角色.docx");boolean fileExists = myFile.exists();//判断是否为文件boolean isFile()//实例化 File,传入一个文件路径File myFile = new File("mywork");boolean myFileIsFile = myFile.isFile();//判断是否为文件夹boolean isDirectory()//得到当前文件夹下的所有子文件,此时返回对象为File数组File[] listFiles()//实例化 File,传入一个文件路径File myFile = new File("mywork");// 使用 for 循环 语句遍历子文件for(File file : myFile.listFiles()){System.out.println(file.getName());}//得到当前文件的父文件实例(上一级文件夹)File getParentFile()//实例化 File,传入一个文件路径File myFile = new File("mywork/201408 人物角色.docx");File parentFile = myFile.getParentFile();//得到当前文件的大小,单位为bytelong length()File myFile = new File("mywork/201408 人物角色.docx");long size = myFile.length();System.out.println(myFile.getName()+" 大小为:"+ size/1024 +"kb");
遍历文件夹并得到该文件夹的大小
public static void main(String[] args) {File myfile = new File("mywork");long total = 0;for(File file: myfile.listFiles()){total = total+ file.length();}System.out.println(total/1024+"kb");}
构造函数
/*没有static 关键字没有返回对象,连void都不需要写方法名==类名称*/public File(String pathname) {}
当我们执行实例化的时候,其实就是执行构造函数,同时搭配new关键字.
new File(myfile,"201408 项目发布通知模板.xlsx");//执行下面的构造函数public File(File parent, String child) {//这个构造函数的第一个参数是父文件实例,//第二个参数子文件的名称,通过这个也可以得到一个文件,我们运行看看}
默认构造函数
public class CustomFile{//类没有内容时会默认创建一个空参数的构造函数public CustomFile(){}}
类的实例化必须通过构造函数来才能完成的,所以如果用户没有自定义那么系统就给一个默认的。
默认构造函数的实例化
CustomFile file = new CustomFile();
对象的属性和方法
对象的属性
对象的属性就是在一个类中创建的变量
private String name;
例子
public class CustomFile{private String name;private File parent;public CustomFile(String name){this.name = name;}public CustomFile(File parent,String name){this.parent = parent;this.name = name;}}
这个时候的this其实指的就是CustomFile类被实例化后的对象,this . name就是指private String name;这个变量,
this.name = name; 就是说给属性name赋值,值是参数name,
我们把代码的参数名称换一下,大家可能更容易理解
public class CustomFile{private String name;private File parent;public CustomFile(String _name){this.name = _name;}public CustomFile(File _parent,String _name){this.parent = _parent;this.name = _name;}//新增类方法public String getSize(){File file = new File(this.name);long size = file.length();return size/1024+"kb";}}
对象方法
没有static关键字
除此之外,静态方法是不能获取对象属性的,只有对象方法才能获取对象属性
ArrayList
ArrayList本质是动态数组对象,可以方便的存储集合对象,我们一般会将同一类型的数据存储在ArrayList中
import java.util.ArrayList;// 这里的 Java 对象类型可以是任意的对象类型// 比如 String、Integer、CustomFile 等// 这里的 <> 是 Java 泛型的规范,以后我们还会介绍ArrayList<Java 对象类型> list = new ArrayList<>();
add()方法
例子
import java.util.ArrayList;public class ArrayListTest1{public static void main(String[] args){// 创建一个 ArrayList 存储字符串集合ArrayList<String> strs = new ArrayList<>();// 添加数据到 ArrayList 实例里strs.add("张三");strs.add("李四");}}
get/size方法
import java.util.ArrayList;public class ArrayListTest1 {public static void main(String[] args) {// 创建一个 ArrayList 存储字符串集合ArrayList<String> strs = new ArrayList<>();// 添加数据到 ArrayList 实例里strs.add("张三");strs.add("李四");// 获取集合的长度int size = strs.size();// 使用 for 循环迭代每一条记录for(int i=0;i<size;i++){// 根据索引获取值,值的类型是 StringString str = strs.get(i);System.out.println(str);}}}
