设定Java环境
我此前安装过IntelliJ IDEA,因此已经有JDK-17
JDK与SDK的关系:
JDK | SDK | 关系 |
---|---|---|
Java Development Kit(Java开发工具包) | soft development kit (软件开发工具包) | JDK是SDK的子集 |
使用cmd键入javac
,如果返回javac相关信息,说明jdk环境设置正确。
Java的工作流程
编译源代码——编译器(javac)编译——输出字节码.class——Java虚拟机(JVM)运行
main():程序的起点,不论程序有多大(包含多少个类),一定都会有一个main()来作为程序的起点。
程序基本语法
- 语句以分号结束;
- 以两条斜线开始的行是注释 //
- 类型+名称 来声明变量
int weight;
- 类和方法都必须定义在花括号中
- 一个等号:赋值运算符;两个等号:等号运算符
- 可以把boolean测试放在括号中
while(x==4)
- print 输出后在同一行;println 换行输出
3种循环
Java有三种循环结构
while循环、do-while循环、for循环
注意:while循环括号中的条件判断,只能是True和False,不能用0,1代替。
// 这是错误的!
int x = 1;
while(x) { }
while循环示例:
public class whileloop {
public static void main (String[] args) {
int x = 1;
System.out.println("Before the Loop");
while(x<4) {
System.out.println("In the Loop");
System.out.println("Value of x is "+x);
x = x+1;
}
System.out.println("The loop is done");
}
}
Before the Loop
In the Loop
Value of x is 1
In the Loop
Value of x is 2
In the Loop
Value of x is 3
The loop is done
条件分支
if - else条件语句
public class IFTest {
public static void main (String[] args){
int x=2;
if (x==3) {
System.out.println("x must be 3");
}
else {
System.out.println("x is not 3");
}
}
}
x is not 3
专家术语学习机
作用:3组单字随机挑出来排列组合输出。
public class PhraseOMatic {
public static void main (String[] args) {
// 专家术语
String[] wordListOne = {"rebellion","996-work","sociological","swelter","html","adulation"};
String[] wordListTwo = {"clown","conceive","surge","embodiment","embody"};
String[] wordListThree = {"antecedent","dwinding","lyrics","piety","rambler","里世界郊游"};
// 计算每一组有多少个术语
int oneLength = wordListOne.length;
int twoLength = wordListTwo.length;
int threeLength = wordListThree.length;
// 产生随机数字
int rand1 = (int) (Math.random() * oneLength);
int rand2 = (int) (Math.random() * twoLength);
int rand3 = (int) (Math.random() * threeLength);
// 组合出专家术语
String phrase = wordListOne[rand1]+" " +wordListTwo[rand2]+" "+wordListThree [rand3];
// 输出
System.out.println("What we need is a "+phrase);
}
}
What we need is a 996-work surge piety
生成随机数时,我们先用random()函数返回0-1之间的随机数,乘以数组长度后取整。
取整:浮点数转换为整型
> int x = (int) 24.6;
练习
排排看:要求输出 a-b c-d
public class Shuffle1 {
public static void main(String[] args) {
int x = 3;
if (x > 2) {
System.out.print("a");
}
x = x - 1;
while (x > 0) {
System.out.print("-");
if (x==2) {
System.out.print("b c");
}
if (x==1) {
System.out.println("d");
}
x = x-1;
}
}
}
泳池迷宫
要求输出:
a noise
annoys
an oyster
public class PoolPuzzleOne {
public static void main(String [] args){
int x=0;
while(x<1) {
System.out.print("a");
if (x<1) {
System.out.print(" ");
}
x = x+1;
if (x>0) {
System.out.println("noise");
x = x - 1;
}
x = x+2;
}
if(x>1) {
System.out.println("annoys");
x = x+1;
}
if(x<4){
System.out.print("an");
x = x-2;
}
System.out.println(" oyster");
}
}