Java ——基础语法

时间:2023-03-08 21:57:20
package myhello; // 本类所在的包的路径

import af.util.AfMath; // 导入对应的类

import java.util.Random; // 导入随机数的类

public class HelloWorld
{ public static void main(String[] args)
{
int a = ;
int i;
int total = ;
int score = ;
System.out.println(a > );
// 空语句 只有一个 ;
;
// 复合语句 {} 包含的
{
;
}
// if 语句
if (score > )
System.out.println("及格");
else
System.out.println("不及格"); for (i = ; i <= ; i++)
{
total += i * i;
}
System.out.println(total); // break 为跳出单层循环 // 创建数据对象
int[] b = new int[];
// 等号右侧:创建了一个数组对象
// 等号左侧:变量 b 称为该对应的引用
// 称作 变量 b 指向了一个对象
// 有时也简称为: b 是一个对象,或 b 是对象的名字 b[] = ;
b[] = ;
b[] = ; int[] arr = { , , , }; System.out.println(arr.length); // arr[4] = 128; 数组越界 // 对应与引用
int[] c = { , , , };
int[] d = c;
// c 指向了一个对象
// c 和 d 指向相同的对象
// c 和 d 都是该对象的引用
d[] = ;
for (int k = ; k < ; k++)
{
System.out.print(c[k] + " ");
} // 空对象
// null 表示一个引用不指向任何对象
int[] e = { , , , };
int[] f = e;
e = null; // 空指针错误
/*
* for (int t = 0; t < 4; t++) { System.out.print(e[t]+" "); }
*/
for (i = ; i < ; i++)
{
System.out.print(f[i] + " ");
} // 类 class
// 类:类型,描述某一类事物的共性
// 对象:一个具体实例
// 用来描述一种数据类型
// 一个class可以若干基本类型的组合
Student s1 = new Student();
s1.id = "";
s1.name = "Jenrry";
s1.sex = true;
s1.cellphone = "";
// Student 是一个类型
// 所有的 Student 都有 id,name,sex,cellphone这几个属性
// s1是一个Student 类型的对象
// 数组
Student[] s2 = new Student[]; // 类的嵌套
s1.cards.bankCardNumber = "";
s1.cards.schoolCardNumber = ""; // java 会有默认值 // 类的方法
// 类.属性:描述 类有什么
// 类.方法:描述 类能做什么
// 属性命名一般使用名词性短语 方法一般是动词性短语
Student s3 = new Student();
s3.show();
s3.show2(); // 获取最大指
int[] a1 = { , , };
int[] aa1 = { , , , };
int result = ;
for (i = ; i < a1.length; i++)
{
if (a1[i] > result)
{
result = a1[i];
}
}
System.out.print("\n");
System.out.print("最大值:" + result);
MyMath a2 = new MyMath();
System.out.print("\n");
a2.getMax(aa1);
int result2 = a2.getMax2(aa1);
System.out.print("\n");
System.out.print("最大值:" + result2); // return语句执行后,函数不再往下执行,直接退出方法
MyMath n = new MyMath();
boolean res = n.check2(aa1);
System.out.print("结果为:" + res); // 给定一个int值,结果打印一个三角形
MyMath n2 = new MyMath();
System.out.print("\n");
n2.print();
n2.print(-);
// 数组里能被8整除
int[] arr2 = { , , , , , , , , , };
MyMath n3 = new MyMath();
int[] result3 = n3.find8(arr2); // 返回类型可以是一个对象
Student stu = n.createNew("", "你好"); // 像素
Screen s = new Screen();
s.height = ;
s.width = ;
int p = s.pixel(s.width, s.height);
System.out.println("像素值是:" + p);
// 用 that指定
int p2 = s.pixel2(s);
System.out.println("像素值2是:" + p2);
// 当前对象 this
int p3 = s.pixel3();
System.out.println("像素值3是:" + p3); // 显示从 m,n之前所有的质数 用到this
MyMath n4 = new MyMath();
n4.showPrimes(, );
// this. 一般可以省略 重名不能省略 // 有一个换游戏币的机器,可以投1元、5、10元,最后按出货按钮,可以吐出游戏币
// 每个游戏币=1元人民币
Machine n5 = new Machine(); n5.insertCash();
n5.insertCash();
n5.insertCash();
// 出货
int coins = n5.exchange();
System.out.println("拿到了" + coins + "个游戏币"); // 用户输入:数组data
// 把打他数组里面,所有的质数都放到result
PrimeFilter filter = new PrimeFilter();
int[] a4 = { , , , };
int[] a5 = { , , , };
filter.put(a4);
filter.put(a5);
int[] numbers = filter.values();
// 对象=属性+方法
// 属性就是数据
// 方法就是算法
// 对象就是数据和算法的整合体
// 给它所需的数据>>让它干活>>取出结果
// 面向对象程序设计 // 访问修饰符
// public private
// 可见性
// private 不可访问,即不可见
// public 可以访问,即可见 // 构造方法
// 用于构造对象的方法 当创建对象时调用的方法
// 规则: 方法名与类名相同;无返回值
Student2 stu2 = new Student2("", "Jenrry", true);
// 默认构造方法 无参数
// 如果没有构造方法,java编译器会默认一个空的构造方法
/*
* public Student2() {
*
* }
*
*/ // 对象的销毁
// 程序员只管创建对象,不管销毁对象,对象的销毁由系统自动完成
// 当对象不再被使用时,由垃圾回收机制GC自动回收 GC: Garbage Collect
// 对象不再被使用。即对象失去引用 // extends 继承
// 在 java语言里,用exends来表示两个类的父子关系
// public class B extends A
// 表示B继承A
// A:父类 B:子类
// 当B继承于A时,自动继承A中的public 属性/方法
MyVideoFile file = new MyVideoFile();
file.size = ;
file.name = "文档";
file.duration = ;
file.info();
file.play();
file.stop(); // 重写
// 如果父类的方法不满足要求,则可以在子类里重写一遍
file.info(); // 父类构造方法
// 子类会先调用父类构造方法 再调用子类的构造方法
// 可以用 super 制定调用哪个构造方法
// 创建一个对象时,构造方法被调用
Child ch = new Child();
System.out.println("exit"); // 单根继承
// java语言里,一个类只能extend是一个父类
// 继承只能有1个父亲,但是可以有一个继承链
// 即 A -> B -> C -> D ……
// 看继承链 右键 Quick Type Hierarchy
// 在 java 语言中,Object 类是所有类的父类 上面的快捷键可以展示出来
// 如果一个类没有指定父类,则它默认父类就是 Object // 重写 toString() 方法
// toString() 是 Object 的一个方法
Student Stu = new Student();
Stu.id = "";
Stu.name = "";
Stu.sex = true;
System.out.println(Stu);// 重写 toString 函数,修改 Stu 显示的格式 // 多态
// java里,包含:重载 Overload ;重写 Override ;泛型
// 有一个饼干,是苹果味饼干
Pie pi = new ApplePie();
// 有一个宝宝
Baby bb = new Baby();
// 宝宝要吃饼干
bb.eat(pi);
// 语法上:
// 1. 子类转换成父类顺理成章(隐式转换)
// 如上 Pie pi = ApplePie();
// 2. 父类转换成子类型要谨慎 需要显式转换 // 多态
MyVideoFile f1 = new MyVideoFile();
f1.name = "abc.mp4";
f1.size = ;
f1.duration = ; MyFile file2 = f1;
file2.info();
// 注意 当调用一个方法是,不是看引用(声明)的类型,而是看对象的实际类型
// file 指向的是一个MyVideoFile对象,因而调用的是子类的info()方法
// 在 java里,由于所有的类型都是Object的直接或者间接子类
// 所以。 Object x = new MyVideoFile(); 是没有问题的。 // 包
// 右键点击包名, show in -> System Explorer
// 建立目录是用 . 分隔
// 一个类XXX,对应的文件是 XXX.java
// 类的全路径: af.util.AfMath
// 类的文件路径: af/util/AfMath.java // 导入类
AfMath a8 = new AfMath(); // 类改名
// 左窗口右键对应的类 -> refactor->rename
// 改属性名、方法名 对应属性/方法 右键-> refactor -> rename // 快捷键
// 注释:选中要注释的行 ctrl+ /
// 查看定义: CTRL+鼠标点击
// 打开提示: ATL+ /
// 格式化选中代码: CTRL+SHIFT+F // 静态方法(全局方法)
// 该方法与类的关系不大。随便拷贝到别的类里也仍然可以运行,没有语法错误;没有this对象
// 动态方法
// 该方法与类关系密切。如果拷贝到别的类里就失去意义,有语法错误。
// 静态方法用 static 修饰
// 静态方法调用无需创建对象,因为是一个全局的
boolean result5 = Example.isPrime(); // Math 类
// 有很多数据计算相关的静态方法
// 和 String类似,Math 也是 java 语言自带的类
// abs(a): 求a的绝对值
// pow(a,b): 求a的b次幂
// sqrt(a) : 求a的平方根
// round(a): 四舍五入
// sin/cos/tan:
// 应用 Math. // 程序入口:
// main 方法,仅有一个格式
// 可以有多个,用于类的调试
// 如有多个 入口需指定 // 字符串
// 字符串长度 String s = ""; int n = s.length();
// 注:中文字符和英文字符都只占一个字符
// 空字符串和null是两回事;空字符串是一个正常的字符串对象;null不指向任何对象
// 截断 substring(begin,end) ; s.substring
// 相等 equals 注:不能使用 == 符号来验证
// 比较 compareTo
// 忽略大小写比较 compareToIgnoreCase()
// 格式化 format
// 查找 indexOf
// 前缀 startWith()
// 后缀 endsWith // 基本类型与包装类型
// 在java里面。每一个基本类型都对应一个包装类型
// long -> Long
// int -> Integer
// short -> Short
// byte -> Byte
// double -> Double
// float -> Float
// boolean -> Boolean
// 包装类型: 将对应的基本类型封装在内,得到一个类大概就是这种形式
// class Integer
// {
// private int value = 0;
// ... Getter/Setter/...方法
// }
// 使用Integer等包装类,就可以统一用“对象”的思路;来处理问题
// 所有的类都是Object的子类,Interger也是,但 int,double,boolean 却不是,他们是基本的数据类型
// Java是面向对象的编程语言,一切都是对象,但是为了编程的方便还是引入了基本数据类型,为了能够将这些基本数据类型当成对象操作,Java为每一个基本数据类型都引入了对应的包装类型
// 基本类型和包装类型的转换
// Integer ai= new Integer(10);
// int bi = ai.intValue();
// // 也可以简写,java支持自动转换
// Integer ki =123;
// int mi = ki;
// 数值-> String
// int -> String
// String s = String.valueOf(123);
// String -> int
// int a = Integer.valueOf("123"); // 为什么要设计这些包装类:
// 1. 提供一些用于转换的方法;
// 2. 将所有类型统一成类的范围,都是Object的子类 // 控制台
// 在上个世纪,在图形界面出现之前、一种基于文字的用户交互界面
AfConsole cf = new AfConsole();
cf.print("请输入用户名:");
String username = cf.readString("");
cf.print("请输入密码:");
String password = cf.readString(""); if (password.equals(""))
{
cf.println(username + ",你好!欢迎进入系统!");
} else
{
cf.println("密码错误!");
} // 随机数
// Random 类是JDK里自带的基本类
// java.util.Random
// 使用Random可以生成随机数
// Random rand = new Random();
// int s = rand.nextInt(1000);
// nextInt(1000)表示生成一个0~1000 的随机数
Random rand = new Random();
for (i = ; i < ; i++)
{
int sr = rand.nextInt();
System.out.println("生成随机数:" + sr);
}
// 抽3个人获奖 ,不能重复
int[] resultr = new int[];
int count = ;
Random rand2 = new Random();
while (count < )
{
// 抽一个幸运员工。sra是它的号码
int sra = rand2.nextInt();
// 检查sra是否已经中过奖,检查sra是否在result里
boolean exist = false;
for (i = ; i < count; i++)
{
if (resultr[i] == sra)
{
exist = true;
break;
}
}
if (exist)
{
continue;
} else
{
resultr[count] = sra;
count++;
}
} // 字符
// 一个字符 char c1 = 'A';
// 字符编码
// 地球上所有的文字和符号都有一个编码Unicode,其中,把 0 -128 之前的称为 ASCII码,仅英文、数字、英文标点符号等,对应键盘上的按键 // 字符与字符串
// String -》 char
// String str = "afanihao阿发你好";
// char ch = str.charAt(8);//下标从0开始计数
// char[] chs= str.toCharArray();
// char -> String
// char[] chs = {'阿','发'.'你'.'好'};
// String str = new String(chs,1,3);
// str += '的'; // 在字符串字符中查找字符
// String str ="afanihao阿发你好";
// int p = str.indexOf('发');
// System.out.println("位置" + p); // 容器:存储对象的东西
// 容器是一个设计上的术语,不是一个语法的概念
// 比如说,数组就是一个容器 // 链表: 一种组织数据的方式
Monkey m1 = new Monkey(, "");
Monkey m2 = new Monkey(, "");
Monkey m3 = new Monkey(, "");
Monkey m4 = new Monkey(, ""); m1.next = m2;
m2.next = m3;
m3.next = m4;
m4.next = null; Monkey node = m1;
while (node != null)
{
System.out.println("链表中的节点:" + node);
node = node.next;
} // 链表插入和删除节点
// 1.插入到末尾
Monkey m5 = new Monkey(, "");
m4.next = m5;
// 正规写法,从头开始
Monkey tail = m1;
while (true)
{
if (tail.next == null)
break;
tail = tail.next;
}
tail.next = m5;
// 2.插到头节点之后
Monkey head = m1;
m5.next = m1.next;
m1.next = m5; // 3.插到300 之后
node = m1;
while (node != null)
{
if (node.id == )
{
m5.next = node.next;
node.next = m5;
break;
}
node = node.next;
} // 插入节点
// 有头链表:用一个固定的加节点来充当头节点。
// 此节点不算作链表长度,仅用于简化算法
// 有头链表的构造
// 创建一个假节点,作为链表的头节点
Monkey head1 = new Monkey(, "");
head1.next = m1;
// 遍历
Monkey m = head1.next;
while (m != null)
{
System.out.println("链表");
m = m.next;
}
// 有头链表:插入节点
// 直接插入假节点后面
m5.next = head1.next;
head1.next = m5;
// 有头链表:删除节点200
Monkey node1 = head.next;
Monkey prov = head1;
while (node1 != null)
{
if (node1.id == )
{
prov.next = node1.next;
break;
}
prov = node1;
node1 = node1.next;
}
// 或者采用如下
Monkey node3 = head1;
while (node.next != null)
{
if (node.next.id == )
{
node.next = node.next.next;
break;
}
node = node.next;
} // 链表只是容器的一种实现方法 } }
package myhello;

import java.io.BufferedReader;
import java.io.InputStreamReader; public class AfConsole
{
BufferedReader reader; public AfConsole()
{
InputStreamReader n = new InputStreamReader(System.in);
reader = new BufferedReader(n);
} // 输出显示一个字符串
public void print(String s)
{
System.out.print(s);
} // 输出显示一个字符串,并换行
public void println(String s)
{
System.out.println(s);
} // 从控制台读取用户输入,读取一个字符串
// 如果用户直接按了回车,则返回默认值
public String readString(String defValue)
{
try
{
return reader.readLine();
} catch (Exception e)
{
return defValue;
}
} // 从控制台读取用户输入,读取一个整数
// 如果用户直接按了回车,则返回默认值
public int readInt(int defValue)
{
try
{
String s = readString(null);
return Integer.valueOf(s);
} catch (Exception e)
{
return defValue;
}
}
}
package myhello;

public class ApplePie extends Pie
{ public ApplePie()
{
// TODO Auto-generated constructor stub
} }
package myhello;

public class Baby
{ public void eat(Pie p)
{ } }
package myhello;

public class Child extends Parent
{ public Child()
{
// TODO Auto-generated constructor stub
// 显示指定父类的那个构造函数
// 子类会默认先去父类的构造函数
// 除非先显示的取某个构造函数
super(23);
System.out.println("子类的构造方法……");
} }
package myhello;

public class Example
{ // 判断n是否为质数
public static boolean isPrime(int n)
{
for (int i = 2; i < n; i++)
{
if (n % i == 0)
{
return false;
}
}
return true;
} }
package myhello;

public class Machine
{
public int money = 0;// 机器里投入了多少钱
// 人民币 :1,5,10 public void insertCash(int cash)
{
if (cash > 10)
{
System.out.println("只能识别1元,5元,10元");
return;
}
this.money += cash;
System.out.println("当前余额:" + this.money);
} // 交易完成
public int exchange()
{
int numOfCoin = this.money / 1;
this.money = 0;
System.out.println("交易完成,当前余额清0" + this.money);
return numOfCoin;
}
}
package myhello;

// 一个一个猴子从头至尾排列
public class Monkey
{ public int id;// 编号
public String name; // 名字
public Monkey next; // 它后面的猴子
// null 表示后面没有猴子 public Monkey()
{ } public Monkey(int id, String name)
{
this.id = id;
this.name = name;
} @Override
public String toString()
{
// TODO Auto-generated method stub
// return super.toString();
return String.format("(%s,%s)", name, id);
} }
package myhello;

public class MonkeyList
{
private Monkey head = new Monkey(0, "0"); public MonkeyList()
{
// TODO Auto-generated constructor stub
} // 添加一个对象
public void add(Monkey n)
{
n.next = head.next;
head.next = n;
} // 按编号查找
public Monkey get(int id)
{
Monkey n = head.next;
while (n.next != null)
{
if (n.id == id)
return n;
n = n.next;
}
return null;
} }
package myhello;

public class MyFile
{
public long size;// 文件大小
public String name;// 文件名 // 显示文件信息
public void info()
{
System.out.println("文件" + name + " 大小" + size);
}
}
package myhello;

public class MyMath
{
public void getMax(int[] data)
{
int result = 0;
for (int i = 0; i < data.length; i++)
{
if (data[i] > result)
{
result = data[i];
}
}
System.out.print("最大值:" + result);
} public int getMax2(int[] data)
{
int result = 0;
for (int i = 0; i < data.length; i++)
{
if (data[i] > result)
{
result = data[i];
}
}
return result;
} public boolean check(int[] arr)
{
boolean result = false;
int sum = 0;
for (int i = 0; i < arr.length; i++)
{
sum += sum + arr[i];
if (sum > 100)
{
result = true;
break;
}
}
return result;
} // check 可以写成如下
public boolean check2(int[] a)
{
int sum = 0;
for (int i = 0; i < a.length; i++)
{
sum += sum + a[i];
if (sum > 100)
{
return true;
}
}
return false;
} // 给定一个int值,结果打印一个三角形
public void print(int n)
{
if (n <= 0)
{
System.out.print("小于0");
return;
}
int rows = 0; // 行数
int cols = 0; // 列数
for (int k = 1; k <= n; k++)
{
System.out.print(k + " ");
cols++;
if (cols > rows)
{
System.out.print("\n");
rows++;
cols = 0;
}
}
} // 数组里能被8整除
public int[] find8(int[] arr)
{
int[] temp = new int[arr.length];
int count = 0;
for (int i = 0; i < arr.length; i++)
{
if (arr[i] % 8 == 0)
{
temp[count] = arr[i];
count++;
}
}
int[] result = new int[count];
for (int i = 0; i < count; i++)
{
result[i] = temp[i];
}
return result; } public Student createNew(String id, String name)
{
Student temp = new Student();
temp.id = id;
temp.name = name;
return temp;
} // 判断n是否为质数
public boolean isPrime(int n)
{
for (int i = 2; i < n; i++)
{
if (n % i == 0)
{
return false;
}
}
return true;
} // 显示m,n之前所有的质数
public void showPrimes(int m, int n)
{
for (int i = m; i <= n; i++)
if (this.isPrime(i))
{
System.out.println("质数:" + i);
}
} }
package myhello;

public class MyVideoFile extends MyFile
{
// 父类的public成员自动继承 // 添加子类的特性
public int duration;// 时长 public void play()
{
System.out.println("播放视频" + this.name);
} public void stop()
{
System.out.println("停止播放" + this.name);
} public MyVideoFile()
{
// TODO Auto-generated constructor stub
} @Override
// 右键-source-override/...
public void info()
{
// TODO Auto-generated method stub
// 完全重写
// System.out.println("文件名:" + this.name + ",大小:" + this.size + ",时长:" +
// this.duration);
// 补充
super.info();
System.out.println("时长:" + this.duration);
} }
package myhello;

public class Parent
{
int a;
public Parent()
{
// TODO Auto-generated constructor stub
System.out.println("父类的构造方法……");
}
public Parent(int a)
{
this.a = a;
} }
package myhello;

public class Pie
{ public Pie()
{
// TODO Auto-generated constructor stub
} }
package myhello;

public class PrimeFilter
{
public int[] result = new int[512];
public int total = 0; // 用户输入:数组data
// 把打他数组里面,所有的质数都放到result
public void put(int[] data)
{
for (int i = 0; i < data.length; i++)
{
if (this.isPrime(data[i]))
{
this.result[total] = data[i];
this.total += 1;
}
}
} public boolean isPrime(int n)
{
for (int i = 2; i < n; i++)
{
if (n % i == 0)
{
return false;
}
}
return true;
} // 取出最终过滤得到所有的质数
public int[] values()
{
int[] r = new int[total];
for (int i = 0; i < this.total; i++)
{
r[i] = this.result[i]; }
return r;
} }
package myhello;

public class Screen
{
public int width;
public int height; public int pixel(int v, int h)
{
return v * h;
} public int pixel2(Screen that)
{
int result = that.width * that.height;
return result;
} public int pixel3()
{
int result = this.height * this.width;
return result;
}
}
package myhello;

public class Student
{
public String id;
public String name;
public boolean sex;
public String cellphone;
// 类的嵌套
public StudentCards cards = new StudentCards(); // 类的方法 public void show()
{
System.out.print("\n");
for (int i = 0; i < 10; i++)
{
System.out.print("报数 " + (i + 1));
}
}
@Override
public String toString()
{
// TODO Auto-generated method stub
// return super.toString();
String s = "学号:"+ id+",姓名:"+name;
if (sex)
{
s = s+ ",性别:男";
}
else
{
s = s + ",性别:女";
}
return s;
}
public void show2(int maxNumber)
{
System.out.print("\n");
for (int i = 0; i < maxNumber; i++)
{
System.out.print("count " + (i + 1));
}
} }
package myhello;

public class Student2
{
public String id;
public String name;
public boolean sex; // 构造方法
public Student2(String id, String name, boolean sex)
{
this.id = id;
this.name = name;
this.sex = sex;
}
// 默认构造方法 无参数
public Student2()
{
this.id = "000";
this.name = "Jenrry";
this.sex = true;
}
}
package myhello;

public class StudentCards
{
public String schoolCardNumber;
public String bankCardNumber;
}