1.通过for循环,使用*打印直角三角形。
public class Zhijiao {
public static void main(String[] args){
for (int i = 0; i < 5; i++) {
for (int j = 0; j < i; j++) {
System.out.print("*");
}
System.out.println();
}
}
}
2.使用数组输出唐诗《春晓》。
public class ShuZuPoetry {
public static void main(String[] args){
char arr[][] = new char[4][];
arr[0] = new char[]{'春','眠','不','觉','晓'};
arr[1] = new char[]{'处','处','闻','啼','鸟'};
arr[2] = new char[]{'夜','来','风','雨','声'};
arr[3] = new char[]{'花','落','知','多','少'};
for(int i = 0; i < arr.length; i++){ //控制行数,为4行
for(int j = 0; j < arr[i].length; j++){ //控制列数,为5列
System.out.print(arr[i][j]); //输出每个元素的值
}
if(i%2==0){
System.out.println(',');
} else
System.out.println('。');
}
}}
3.使用嵌套for循环输出九九乘法表,格式如下:
public class ChengFa99 {
public static void main(String[] args){
for (int i = 1;i <= 9;i++){
for (int j = 1;j <= i;j++){
System.out.print(i + "*" + j + "="+ i*j + "\t");
}
System.out.println();//换行
}
}
}
二、面向对象
1.请创建一个名为Student的类,它有四个属性:name(姓名),age(年龄),aScore(a成绩)bScore(b成绩)。请为这个类提供一个构造方法,输出学生姓名,一个getAverageScore方法,用于输出学生a与b成绩的平均成绩,并举例验证。
//2.1 Student
public class Student {
private String name;
private int age;
private double aScore;
private double bScore;
public Student(String name, int age, double aScore, double bScore){
this.name = name;
this.age = age;
this.aScore = aScore;
this.bScore = bScore;
}
public String getName() {
return name;
}
public double getAverageScore() {
return (double) (aScore + bScore) / 2;
}
public static void main(String[] args) {
Student stu = new Student("Tom", 18, 80, 90);
System.out.println("学生姓名:" + stu.getName());
System.out.println("平均成绩:" + stu.getAverageScore());
}
}
2.请创建一个名为Shape的接口,它有两个抽象方法:getArea(获取面积)和getPerimeter(获取周长)。请实现这个接口的一个子类:Circle(圆形),并为它提供合适的实现方法,并举例验证。
interface Shape {
double getArea();
double getPerimeter(); }
class Circle implements Shape {
private double radius;
public Circle(double radius) {
this.radius = radius; }
@Override
public double getArea() {
return Math.PI * radius * radius; }
@Override
public double getPerimeter() {
return 2 * Math.PI * radius; } }
public class ShapeTest {
public static void main(String[] args) {
Circle circle = new Circle(2.5);
System.out.println("圆的面积为:" + circle.getArea());
System.out.println("圆的周长为:" + circle.getPerimeter());
}}
3.请创建一个名为Animal的父类,它有两个属性:name(名称),legs(腿的数量)。请为这个类提供一个构造方法,用于输出动物的叫声。请创建一个名为Dog的子类,它继承了Animal类,并重写构造方法,用于输出“汪汪汪”,并举例验证。
public class Animal {
private String name;
private int legs;
public Animal(String name, int legs) {
this.name = name;
this.legs = legs;
System.out.println(name + " 发出了一声叫声");
}
}
class Dog extends Animal {
public Dog(String name, int legs) {
super(name, legs);
System.out.println("汪汪汪");
}
public static void main(String[] args) {
Dog dog = new Dog("小狗", 4);
}
}
三、图像化界面
1、通过JLabel标签,实现如下图形用户界面(欢迎进入水果超市!)
import javax.swing.*;
import java.awt.*;
public class Fruit {
public static void main(String[] args) {
JFrame frame = new JFrame("JFrame窗口");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400, 300);
// 创建欢迎标签
JLabel welcomeLabel = new JLabel("欢迎进入水果超市", JLabel.CENTER);
welcomeLabel.setFont(new Font("黑体", Font.PLAIN, 20));
frame.getContentPane().add(welcomeLabel, BorderLayout.SOUTH);
// 创建水果图片标签
ImageIcon icon = new ImageIcon("D:\\Java\\2023.java\\Char\\src\\Day7\\Fruit.jpg");
JLabel imageLabel = new JLabel("", icon, JLabel.CENTER);
frame.getContentPane().add(imageLabel, BorderLayout.CENTER);
frame.setVisible(true);
}
}
2. 实现如下图形用户界面,点击加法按钮,将两个文本框数值进行加法运算显示在最后一个标签中。
import java.awt.event.*;
import java.awt.*;
import javax.swing.*;
public class Caculate {
public static void main(String[] args) {
JFrame jf = new JFrame("加法窗口");
jf.setLayout(new FlowLayout()); //设置布局为流式布局
jf.setSize(350, 350);
jf.setLocation(200, 200);
JTextField jt1 = new JTextField(10); //创建两个文本输入框
JTextField jt2 = new JTextField(10);
JButton jb = new JButton("加法");//创建按钮
Label jl = new Label("+"); //创建标签
JLabel jl2 = new JLabel("=");
JLabel jl3 = new JLabel();
jb.addActionListener(new ActionListener() {//为按钮添加监听事件
@Override
public void actionPerformed(ActionEvent e) {
//JLabel jl3 = new JLabel(); //将jl3进行实例化
if (jt1 != null && jt2 != null) { //获取文本框中的数据
int a1 = Integer.parseInt((jt1.getText())); //把文本框中的数据强制转化为double类型
int a2 = Integer.parseInt((jt2.getText()));
jl3.setText("" + (a1 + a2)); //这里的""表示强制转化字符串
}
}
});
//把组件添加进去
jf.add(jt1);
jf.add(jl);
jf.add(jt2);
jf.add(jl2);
jf.add(jl3);
jf.add(jb);
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jf.setVisible(true); //设置窗口可见
}
}
3.通过单击右键实现弹出式菜单,结果如图所示。
import javax.swing.*;
import java.awt.event.*;
public class TanChu extends JFrame {
private JPopupMenu popupMenu;
private JMenuItem viewItem;
private JMenuItem newItem;
private JMenuItem exitItem;
public TanChu() {
setSize(300, 200);
// 创建弹出式菜单
popupMenu = new JPopupMenu();
viewItem = new JMenuItem("查看");
newItem = new JMenuItem("新建");
exitItem = new JMenuItem("退出");
// 将菜单项添加到弹出式菜单中
popupMenu.add(viewItem);
popupMenu.add(newItem);
popupMenu.addSeparator(); // 添加分隔符
popupMenu.add(exitItem);
// 为退出菜单项添加事件监听器
exitItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
// 将弹出式菜单添加到窗口上
addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent e) {
if (e.isPopupTrigger()) {
popupMenu.show(e.getComponent(), e.getX(), e.getY());
}
}
public void mouseReleased(MouseEvent e) {
if (e.isPopupTrigger()) {
popupMenu.show(e.getComponent(), e.getX(), e.getY());
}
}
});
}
public static void main(String[] args) {
TanChu frame = new TanChu();
frame.setVisible(true);
}
}
四、线程题
1、模拟3个老师同时给10个小朋友发礼品,每个老师相当于一个线程。
public class TeacherGift implements Runnable {
private int teacherId; // 老师编号
private static int studentCount = 10; // 学生数量
private static int currentStudent = 1; // 当前已发礼物的学生编号
private static int[] giftCount = {0, 0, 0}; // 老师送出礼物的数量
private static int totalGiftCount = 0; // 总共送出礼物的数量
public TeacherGift(int teacherId) {
this.teacherId = teacherId;
}
@Override
public void run() {
while (currentStudent <= studentCount) {
synchronized (TeacherGift.class) { // 同步锁
if (currentStudent % 3 == teacherId) {
System.out.println("理科老师 " + Thread.currentThread().getName() + " 给小朋友 " + currentStudent + " 发礼物");
giftCount[teacherId]++;
totalGiftCount++;
currentStudent++;
}
}
try {
Thread.sleep(1000); // 等待1秒
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println(Thread.currentThread().getName() + " 共送出礼物 " + giftCount[teacherId] + " 个。");
}
public static void main(String[] args) {
TeacherGift teacher1 = new TeacherGift(0);
TeacherGift teacher2 = new TeacherGift(1);
TeacherGift teacher3 = new TeacherGift(2);
new Thread(teacher1, "物理老师").start();
new Thread(teacher2, "化学老师").start();
new Thread(teacher3, "生物老师").start();
}
}
2、编写一个程序,创建两个线程,要求分别输出26个字母。在输出结果时,要显示是哪个线程输出的字母。
public class Letters26 implements Runnable {
private final char startChar; // 起始字母
private final int threadId; // 线程编号
private static volatile int currentChar = 'A'; // 当前输出的字母
public Letters26(char startChar, int threadId) {
this.startChar = startChar;
this.threadId = threadId;
}
@Override
public void run() {
while (currentChar <'Z') {
synchronized (Letters26.class) { // 同步锁
if (currentChar % 2 == threadId) { // 判断当前字母是否由该线程输出
System.out.println(Thread.currentThread().getName() + ": " + (char) currentChar);
currentChar++;
}
}
}
}
public static void main(String[] args) {
Letters26 printer1 = new Letters26('A', 0);
Letters26 printer2 = new Letters26('B', 1);
new Thread(printer1, "线程1").start();
new Thread(printer2, "线程2").start();
}
}
3、编写一个程序,使用Runnable接口的方式创建两个线程,分别输出从0到10的数,每个线程之间延迟500毫秒,要求输出的结果如下所示:
线程一 : 0,1,2,3,4,5,6,7,8,9,10
线程二 : 0,1,2,3,4,5,6,7,8,9,10
class Shu implements Runnable{
@Override
public synchronized void run() {
System.out.print(Thread.currentThread().getName()+":");
for(int i=0;i<11;i++){
System.out.print(i);
if(i!=10){
System.out.print(",");
}
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println();
}
}
public class RunnableTest {
public static void main(String[] args) {
Shu s=new Shu();
new Thread(s,"线程一").start();
new Thread(s,"线程二").start();
}
}
五、改错题
2.注意hasNext的使用方法
import java.util.*;
public class Gai2 {
public static void main(String[] args) {
ArrayList<String> list = new ArrayList<>();
list.add("s1");
list.add("s2");
list.add("s3");
list.add("s4");
list.add("s5");
System.out.println("按索引检查");
Iterator<String> iterator = list.iterator();
while (iterator.hasNext()) { // 注意 hasNext() 方法的书写
String element = iterator.next();
System.out.println("数据为" + element);
}
}
}