文章目录
💖 配置环境
🌸 CMD 查看本机 JDK 版本命令:
java -version
1. 输出 Hello World!
(1) 新建 Java 文件
文件名:HelloWorld.java
文件内容:
public class HelloWorld //此处的class名需要和文件名一致
{
public static void main(String[] args)
{
System.out.println("Hello World!");
}
}
(2) 打开 CMD 并进入当前文件目录
在当前文件的路径栏,输入 cmd
,回车
(3) 编译并运行
Tips: 按 tap 键可以自动补全文件名
① 编译 HelloWorld.java 文件,生成 HelloWorld.class 文件:javac HelloWorld.java
② 运行 HelloWorld.class 文件:java HelloWorld
(注意无需加 .class 后缀)
2. 输入三个数,输出最大值
文件名:GetMax.java
文件内容:
import java.util.Scanner;
public class GetMax //此处的class名需要和文件名一致
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
int a = sc.nextInt();
int b = sc.nextInt();
int c = sc.nextInt();
int max = a;
if(b > max) max = b;
if(c > max) max = c;
System.out.println(max);
}
}
3. 添加注释
public class Smp2 {
public static void main(String[] args)
{
//单行注释
/* 多行注释
多行注释
*/ 多行注释
System.out.println("This is a simple example!");
System.out.println("A documentation about this program is requested!");
}
}
4. 找Bug
① 该程序有多少处错误?错误原因是什么?
答:两处;数据类型不匹配。
② 请通过修改变量a和b的数据类型的方法改正该程序,并在下面填写修改后能正常编译运行的程序内容:
public class Smp3
{
public static void main(String[] args)
{
// int a;
long a = 3L * 4;
System.out.println(a);
// float b;
double b = 3.2 * 4;
System.out.println(b);
}
}
输出
12
12.8
③ 请不修改变量a和b的数据类型,而是通过强制类型转换的方法改正该程序,并在下面填写修改后能正常编译运行的程序内容:
public class Smp3
{
public static void main(String[] args)
{
int a;
a = (int) (3L * 4);
System.out.println(a);
float b;
b = (float) (3.2 * 4);
System.out.println(b);
}
}
输出
12
12.8
5. 分析表达式结果
💖 源代码
public class Main
{
public static void main(String[] args)
{
int c;
c = 0b10100001 & 0b10000000;
System.out.println(Integer.toBinaryString(c));
c = 0b10001001 | 0b10000000;
System.out.println(Integer.toBinaryString(c));
c = ~0b11011110;
System.out.println(Integer.toBinaryString(c));
c = 0b10010001 ^ 0b10000000;
System.out.println(Integer.toBinaryString(c));
c = 0b11110 << 3;
System.out.println(Integer.toBinaryString(c));
c = 0b10000000100000001010000010000000 >> 3;
System.out.println(Integer.toBinaryString(c));
c = 0b10000000100000101000000010000000 >>> 3;
System.out.println(Integer.toBinaryString(c));
}
}
🌸 运行结果
6. 分数评级
import java.util.Scanner;
public class ScoreTest
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
int score = sc.nextInt();
calLevel(score);
// 以下是测试代码
// for (int i = -20; i <= 120; i += 20)
// {
// System.out.print("分数 " + i + " ");
// calLevel(i);
// }
}
private static void calLevel(int score)
{
if (score > 100)
System.out.println("输入错误");
else if (score >= 90)
System.out.println("优秀");
else if (score >= 80)
System.out.println("良好");
else if (score >= 70)
System.out.println("中等");
else if (score >= 60)
System.out.println("及格");
else if (score >= 0)
System.out.println("不及格");
else
System.out.println("输入错误");
}
}
测试结果