public class Hello
{
public static void main(String args[])
{
System.out.println("Hello!");
}
}
import java.awt.*;
import java.applet.Applet;
public class HelloApplet extends Applet
{
public void paint(Graphics g)
{
g.setColor(Color.red);
g.drawString("Hello!",20,20);
}
}
<html>
<applet code="HelloApplet.class" height=100 width=300>
</applet>
</html>
public class a {
public static void main(String[] args) {
int n = 4;
int[][] nums = new int[n][n];
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (i >= j) {
nums[i][j] = j;
} else {
nums[i][j] = i;
}
}
}
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
System.out.print(nums[i][j] + " ");
}
System.out.println();
}
}
}
import java.util.Scanner;
public class Yang_Hui_Triangle {
public static void main(String[] args) {
Scanner triangle = new Scanner(System.in);
System.out.println("请输入杨辉三角的层数");
int i = 0;
int j = 0;
int n = 0;
int k = 0;
n = triangle.nextInt();
int arr[] = new int[2000];
k = 0;
while (n-- != 0) {
arr[k++] = 1;
for (i = k - 2; i >= 1; i--)
arr[i] += arr[i - 1];
for (i = 0; i < n; i++)
System.out.print(" ");
for (i = 0; i < k; i++) {
System.out.print(" ");
System.out.print(arr[i]);
}
System.out.print("\n");
}
}
}
import java.util.Scanner;
public class Two_dimensional_array {
public static void main(String[] args) {
int arr[][] = new int[1000][1000];
int i = 0;
int j = 0;
int i_max = 0;
int j_max = 0;
int pos = 0;
int flag = 0;
Scanner array = new Scanner(System.in);
System.out.println("请输入二维数组中的行和列");
i_max = array.nextInt();
j_max = array.nextInt();
for (i = 0; i < i_max; i++)
{
for(j = 0; j < j_max; j++)
{
arr[i][j] = array.nextInt();
}
}
for (i = 0; i < i_max; ++i)
{
int max = arr[i][0];
for (j = 1; j < j_max; ++j)
{
if (arr[i][j] > max)
{
max = arr[i][j];
pos = j;
}
}
for (j = 0; j < j_max; ++j)
{
if (arr[j][pos]<max)
{
break;
}
}
if (j == j_max)
{
System.out.println("该鞍点为:"+arr[i][pos]);
flag = 1;
break;
}
}
if (0 == flag)
{
System.out.println("没有鞍点");
}
}
}
import java.util.Scanner;
public class Palindrome_string {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter a string: ");
String str = input.nextLine();
if (isPalindrome(str)) {
System.out.println(str + " is a palindrome.");
} else {
System.out.println(str + " is not a palindrome.");
}
}
public static boolean isPalindrome(String str) {
int i = 0;
int j = str.length() - 1;
while (i < j) {
if (str.charAt(i) != str.charAt(j)) {
return false;
}
i++;
j--;
}
return true;
}
}
public class ComplexNumber {
double real;
double imaginary;
public ComplexNumber(double real, double imaginary) {
this.real = real;
this.imaginary = imaginary;
}
public ComplexNumber add(ComplexNumber n) {
double newReal = this.real + n.real;
double newImaginary = this.imaginary + n.imaginary;
return new ComplexNumber(newReal, newImaginary);
}
public ComplexNumber subtract(ComplexNumber n) {
double newReal = this.real - n.real;
double newImaginary = this.imaginary - n.imaginary;
return new ComplexNumber(newReal, newImaginary);
}
public boolean equals(ComplexNumber n) {
return (this.real == n.real && this.imaginary == n.imaginary);
}
}
public class Person {
String name;
int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public static void main(String[] args) {
Teacher teacher = new Teacher("wzr",20, "jit","professor");
System.out.println("Teacher's name: " + teacher.getName());
System.out.println("Teacher's age: " + teacher.getAge());
System.out.println("Teacher's workfor: " + teacher.getworkfor());
System.out.println("Teacher's title: " + teacher.gettitle());
}
}
class Teacher extends Person {
private String workfor;
private String title;
public Teacher(String name, int age, String workfor, String title) {
super(name, age);
this.workfor = workfor;
this.title = title;
}
public String getworkfor() {
return workfor;
}
public void setworkfor(String workfor) {
this.workfor = workfor;
}
public String gettitle() {
return title;
}
public void settitle(String title) {
this.title = title;
}
}
public class Person2 {
String Name;
char Sex;
int BirthYear;
public Person2()
{
this.Name=null;
this.Sex='M';
this.BirthYear=0;
}
public Person2(String Name,char Sex,int BirthYear)
{
this.Name=Name;
this.Sex=Sex;
this.BirthYear=BirthYear;
}
public void age(int BirthYear)
{
System.out.println("age is:"+(2023 - BirthYear));
}
public void Information()
{
System.out.println("Personal Information:");
System.out.println(Name+"\t"+Sex+"\t");
}
public static void main(String args[])
{
Teacher2 T1= new Teacher2();
T1.Name="ZhangSan";
T1.Sex='F';
T1.WorkFor="JIT";
T1.Title="professor";
T1.EngagedIn="JAVA";
T1.BirthYear = 2003;
T1.Information();
T1.age(2003);
}
}
class Teacher2 extends Person2{
String WorkFor;
String Title;
String EngagedIn;
public Teacher2()
{
this.WorkFor=null;
this.Title=null;
this.EngagedIn=null;
}
public Teacher2(String Name,char Sex,int BirthYear,String WorkFor,String Title,String EngagedIn)
{
super(Name,Sex,BirthYear);
this.WorkFor=WorkFor;
this.Title=Title;
this.EngagedIn=EngagedIn;
}
public void age(int BirthYear)
{
super.age(BirthYear);
}
public void Information()
{
super.Information();
System.out.println("Work for:"+WorkFor);
System.out.println("Profession:"+EngagedIn+"\nTitle:"+Title);
}
}
interface Volume {
double getVolume();
}
class Circle {
protected double radius;
public Circle(double radius) {
this.radius = radius;
}
public double getRadius() {
return radius;
}
public double getArea() {
return Math.PI * radius * radius;
}
}
class Cylinder extends Circle implements Volume {
protected double height;
public Cylinder(double radius, double height) {
super(radius);
this.height = height;
}
public double getHeight() {
return height;
}
public double getVolume() {
return getArea() * height;
}
public double getSurfaceArea() {
return 2 * Math.PI * radius * (radius + height);
}
}
class Cone extends Circle implements Volume {
protected double height;
public Cone(double radius, double height) {
super(radius);
this.height = height;
}
public double getHeight() {
return height;
}
public double getVolume() {
return (1.0 / 3.0) * getArea() * height;
}
public double getSurfaceArea() {
double slantHeight = Math.sqrt(radius * radius + height * height);
return Math.PI * radius * (radius + slantHeight);
}
}
public class Graph {
int edge;
public Graph(int edge)
{
this.edge = edge;
}
public int getedge()
{
return edge;
}
public void setedge(int edge)
{
this.edge = edge;
}
public static void main(String[] args) {
}
}
class Triangle extends Graph{
int Bottom_edge_length;
int height;
public Triangle(int edge,int Bottom_edge_length,int height)
{
super(edge);
this.Bottom_edge_length = Bottom_edge_length;
this.height = height;
}
}
interface Automobile {
void drive();
}
interface Nonautomobile {
void pedal();
}
class VehicleClass implements Automobile, Nonautomobile {
protected String vehicleName;
protected int wheelCount;
public VehicleClass(String vehicleName, int wheelCount) {
this.vehicleName = vehicleName;
this.wheelCount = wheelCount;
}
public String getVehicleName() {
return vehicleName;
}
public int getWheelCount() {
return wheelCount;
}
public void drive() {
System.out.println(vehicleName + " is being driven.");
}
public void pedal() {
System.out.println(vehicleName + " is being pedaled.");
}
}
class BusClass extends VehicleClass implements Automobile {
private int passengerCount;
public BusClass(String vehicleName, int wheelCount, int passengerCount) {
super(vehicleName, wheelCount);
this.passengerCount = passengerCount;
}
public int getPassengerCount() {
return passengerCount;
}
public void drive() {
System.out.println(vehicleName + " is a bus and is being driven.");
}
}
class BicycleClass extends VehicleClass implements Nonautomobile {
private int gearCount;
public BicycleClass(String vehicleName, int wheelCount, int gearCount) {
super(vehicleName, wheelCount);
this.gearCount = gearCount;
}
public int getGearCount() {
return gearCount;
}
public void pedal() {
System.out.println(vehicleName + " is a bicycle and is being pedaled.");
}
}
class BankAccount {
private double balance;
private double interest;
public BankAccount(double balance, double interest) {
this.balance = balance;
this.interest = interest;
}
public double getBalance() {
return balance;
}
public void deposit(double amount) {
balance += amount;
System.out.println("成功存款:" + amount);
}
public void withdraw(double amount) {
if (balance >= amount) {
balance -= amount;
System.out.println("成功取款:" + amount);
} else {
System.out.println("余额不足,取款失败");
}
}
public double getInterest() {
return interest;
}
public void setInterest(double interest) {
this.interest = interest;
System.out.println("成功设置利率:" + interest);
}
}
public class UseAccount {
public static void main(String[] args) {
BankAccount account = new BankAccount(1000.0, 0.05);
double balance = account.getBalance();
System.out.println("当前余额:" + balance);
account.deposit(500.0);
balance = account.getBalance();
System.out.println("当前余额:" + balance);
account.withdraw(200.0);
balance = account.getBalance();
System.out.println("当前余额:" + balance);
double interest = account.getInterest();
System.out.println("当前利率:" + interest);
account.setInterest(0.1);
interest = account.getInterest();
System.out.println("当前利率:" + interest);
}
}
mport java.util.Scanner;
public class ScannerSum{
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int a = sc.nextInt();
int b = sc.nextInt();
int result = a + b;
System.out.println("结果是:"+result);
}
}
mport java.util.Scanner;
public class User {
private String username;
private String pwd;
public User(String username, String pwd) {
this.username = username;
this.pwd = pwd;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPwd() {
return pwd;
}
public void setPwd(String pwd) {
this.pwd = pwd;
}
public static void main(String[] args) {
User[] users = new User[3];
users[0] = new User("user1", "password1");
users[1] = new User("user2", "password2");
users[2] = new User("user3", "password3");
Scanner scanner = new Scanner(System.in);
System.out.print("Please enter your username: ");
String username = scanner.nextLine();
System.out.print("Please enter your password: ");
String password = scanner.nextLine();
boolean found = false;
for (User user : users) {
if (user.getUsername().equals(username)) {
found = true;
if (user.getPwd().equals(password)) {
System.out.println("Login successful!");
break;
} else {
System.out.println("Password is incorrect!");
break;
}
}
}
if (!found) {
System.out.println("User not found!");
}
}
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
public class Time {
public static void main(String[] args) {
String dateTimeStr= "2023-03-22 16:40:30";
DateTimeFormatter formatter02 = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
LocalDateTime localDateTime=LocalDateTime.parse(dateTimeStr,formatter02);
System.out.println(localDateTime);
String format = localDateTime.format(formatter02);
System.out.println(format);
}
import java.text.DecimalFormat;
public class random_number {
public static void main(String[] args) {
double d = Math.random()*100;
DecimalFormat df = new DecimalFormat("0.00");
String str = df.format(d);
System.out.println(str);
}
public class Int {
public static void main(String[] args) {
int count = 0;
double min = - 10.8;
double max = 5.9;
for (int i = (int)min; i < max; ++i) {
if (Math.abs(i) > 6 || Math.abs(i) < 2.1) {
if (i % 1 == 0) {
count++;
}
}
}
System.out.println("There are " + count + " integers the condition.");
}
import java.math.BigInteger;
public class FactorialSum {
public static BigInteger factorial(BigInteger n) {
if (n.equals(BigInteger.ZERO) || n.equals(BigInteger.ONE)) {
return BigInteger.ONE;
} else {
return n.multiply(factorial(n.subtract(BigInteger.ONE)));
}
}
public static BigInteger calculateFactorialSum(int n) {
BigInteger sum = BigInteger.ZERO;
for (int i = 1; i <= n; i++) {
sum = sum.add(factorial(BigInteger.valueOf(i)));
}
return sum;
}
public static void main(String[] args) {
int n = 10;
BigInteger result = calculateFactorialSum(n);
System.out.println("1! + 2! + 3! + ... + " + n + "! = " + result);
}
import java.util.Scanner;
public class InformationEntry {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String name;
int age;
try {
System.out.print("请输入姓名:");
name = scanner.nextLine();
System.out.print("请输入年龄:");
String ageInput = scanner.nextLine();
age = Integer.parseInt(ageInput);
if (age <= 0) {
throw new IllegalArgumentException("年龄必须是一个正整数");
}
System.out.println("姓名:" + name);
System.out.println("年龄:" + age);
} catch (NumberFormatException e) {
System.out.println("年龄输入有误,请输入一个整数年龄");
} catch (IllegalArgumentException e) {
System.out.println(e.getMessage());
}
}
波斯猫方法体打印:一只叫做XXX的,X岁的波斯猫,正在吃小饼干~
狸花猫方法体打印:一只叫做XXX的,X岁的狸花猫,正在吃鱼儿~
泰迪方法体打印:一只叫做XXX的,X岁的泰迪,正在吃骨头,边吃边蹭~
哈士奇方法体打印:一只叫做XXX的,X岁的哈士奇,正在吃骨头,边吃边拆家~
测试类中定义一个方法用于饲养动物
public static void keepPet(ArrayList<???> list) {
// 遍历集合,调用动物的eat方法
}
要求:
a、该方法能养所有品种的猫,但是不能养狗
b、该方法能养所有品种的狗,但是不能养猫
c、该方法能养所有的动物,但是不能传递其他类型
import java.util.ArrayList;
class Animal{
protected String name;
protected int age;
public Animal(String name, int age)
{
this.name = name;
this.age = age;
}
public void eat() {
System.out.println("一只叫做" + name + "的" + age + "岁的动物正在吃东西~");
}
}
class Cat extends Animal{
public Cat(String name, int age){
super(name, age);
}
}
class PersianCat extends Animal{
public PersianCat (String name, int age){
super(name, age);
}
public void eat() {
System.out.println("一只叫做" + name + "的" + age + "岁的波斯猫,正在吃小饼干~");
}
}
class TabbyCat extends Animal{
public TabbyCat (String name, int age){
super(name, age);
}
public void eat() {
System.out.println("一只叫做" + name + "的" + age + "岁的狸花猫,正在吃鱼儿~");
}
}
class Dog extends Animal{
public Dog(String name, int age){
super(name, age);
}
}
class Husky extends Dog {
public Husky(String name, int age) {
super(name, age);
}
public void eat() {
System.out.println("一只叫做" + name + "的" + age + "岁的哈士奇,正在吃骨头,边吃边拆家~");
}
}
class Teddy extends Dog {
public Teddy(String name, int age) {
super(name, age);
}
public void eat() {
System.out.println("一只叫做" + name + "的" + age + "岁的泰迪,正在吃骨头,边吃边蹭~");
}
}
public class AnimalTest {
public static void keepPet(ArrayList<? extends Animal> list) {
for (Animal animal : list) {
animal.eat();
}
}
public static void main(String[] args) {
ArrayList<Animal> animalList = new ArrayList<>();
animalList.add(new PersianCat("小白", 2));
animalList.add(new TabbyCat("小黑", 3));
animalList.add(new Husky("小花", 1));
animalList.add(new Teddy("小黄", 2));
keepPet(animalList);
}
}
import java.util.ArrayList;
import java.util.Comparator;
class MyDate {
private int year;
private int month;
private int day;
public MyDate(int year, int month, int day) {
this.year = year;
this.month = month;
this.day = day;
}
public int getYear() {
return year;
}
public int getMonth() {
return month;
}
public int getDay() {
return day;
}
public void setYear(int year) {
this.year = year;
}
public void setMonth(int month) {
this.month = month;
}
public void setDay(int day) {
this.day = day;
}
public String toString() {
return "MyDate{" +
"year=" + year +
", month=" + month +
", day=" + day +
'}';
}
}
public class Employee {
private String name;
private double sal;
private MyDate birthday;
public Employee(String name, double sal, MyDate birthday) {
this.name = name;
this.sal = sal;
this.birthday = birthday;
}
public String getName() {
return name;
}
public double getSal() {
return sal;
}
public MyDate getBirthday() {
return birthday;
}
public void setName(String name) {
this.name = name;
}
public void setSal(double sal) {
this.sal = sal;
}
public void setBirthday(MyDate birthday) {
this.birthday = birthday;
}
public String toString() {
return "Employee{" +
"name='" + name + '\'' +
", sal=" + sal +
", birthday=" + birthday +
'}';
}
public static void main(String[] args) {
ArrayList<Employee> employees = new ArrayList<>();
employees.add(new Employee("p1", 10000, new MyDate(1990, 1, 1)));
employees.add(new Employee("p2", 20000, new MyDate(1995, 2, 1)));
employees.add(new Employee("p3", 15000, new MyDate(1990, 3, 1)));
employees.sort(new Comparator<Employee>() {
@Override
public int compare(Employee p1, Employee p2) {
int nameCompare = p1.getName().compareTo(p2.getName());
if (nameCompare != 0) {
return nameCompare;
}
else {
MyDate d1 = p1.getBirthday();
MyDate d2 = p2.getBirthday();
if (d1.getYear() != d2.getYear()) {
return d1.getYear() - d2.getYear();
}
else if (d1.getMonth() != d2.getMonth())
{
return d1.getMonth() - d2.getMonth();
} else {
return d1.getDay() - d2.getDay();
}
}
}
});
for (Employee employee : employees) {
System.out.println(employee);
}
}
}
import java.util.Arrays;
import java.util.Scanner;
public class RemoveExtremun{
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String input = scanner.nextLine();
String[] strArray = input.split(" ");
int[] intArray = new int[strArray.length];
for (int i = 0; i < strArray.length; i++) {
intArray[i] = Integer.parseInt(strArray[i]);
}
Arrays.sort(intArray);
for (int i = 1; i < intArray.length - 1; i++) {
System.out.print(intArray[i] + " ");
}
}
import java.io.File;
import java.io.IOException;
import java.io.FileWriter;
public class IsFile {
public static void main(String[] args) {
String directoryPath = "/Users/wzr/Desktop";
String filePath = directoryPath + "/hello.txt";
File directory = new File(directoryPath);
if (!directory.exists()) {
directory.mkdirs();
}
File file = new File(filePath);
if (!file.exists()) {
try {
file.createNewFile();
FileWriter writer = new FileWriter(file);
writer.write("hello world!");
writer.close();
System.out.println("文件已创建并写入内容");
} catch (IOException e) {
e.printStackTrace();
}
} else {
System.out.println("文件已存在");
}
}
}
import java.io.*;
public class MergeAndSortFiles {
public static void main(String[] args) {
String file1Path = "file1.txt"; // 第一个文件的路径
String file2Path = "file2.txt"; // 第二个文件的路径
String mergedFilePath = "merged.txt"; // 合并后的文件路径
mergeAndSortFiles(file1Path, file2Path, mergedFilePath);
}
public static void mergeAndSortFiles(String file1Path, String file2Path, String mergedFilePath) {
try {
FileInputStream file1Input = new FileInputStream(file1Path);
FileInputStream file2Input = new FileInputStream(file2Path);
FileOutputStream mergedOutput = new FileOutputStream(mergedFilePath);
mergeFiles(file1Input, mergedOutput);
mergeFiles(file2Input, mergedOutput);
sortFile(mergedFilePath);
System.out.println("文件合并并排序完成");
} catch (IOException e) {
e.printStackTrace();
}
}
public static void mergeFiles(FileInputStream input, FileOutputStream output) throws IOException {
int data;
while ((data = input.read()) != -1) {
output.write(data);
}
input.close();
}
public static void sortFile(String filePath) {
try {
FileInputStream fileInput = new FileInputStream(filePath);
DataInputStream dataInput = new DataInputStream(fileInput);
int fileSize = dataInput.available();
byte[] data = new byte[fileSize];
dataInput.readFully(data);
dataInput.close();
for (int i = 0; i < fileSize - 1; i++) {
for (int j = 0; j < fileSize - i - 1; j++) {
if (data[j] > data[j + 1]) {
byte temp = data[j];
data[j] = data[j + 1];
data[j + 1] = temp;
}
}
}
FileOutputStream fileOutput = new FileOutputStream(filePath);
DataOutputStream dataOutput = new DataOutputStream(fileOutput);
dataOutput.write(data);
dataOutput.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
import java.io.*;
public class AddSemicolonToFile {
public static void main(String[] args) {
String inputFilePath = "input.txt";
String outputFilePath = "output.txt";
addSemicolonToFile(inputFilePath, outputFilePath);
}
public static void addSemicolonToFile(String inputFilePath, String outputFilePath) {
try {
BufferedReader reader = new BufferedReader(new FileReader(inputFilePath));
FileWriter writer = new FileWriter(outputFilePath);
String line;
while ((line = reader.readLine()) != null) {
String modifiedLine = line + ";";
System.out.println(modifiedLine);
writer.write(modifiedLine + "\n");
}
reader.close();
writer.close();
System.out.println("处理完成");
} catch (IOException e) {
e.printStackTrace();
}
}
}
import javax.swing.*;
import java.awt.*;
public class Calculator extends JFrame {
public Calculator() {
JFrame JWindow = new JFrame("计算器");
JWindow.setBackground(Color.BLACK);
JWindow.setSize(350,310);
JWindow.setLocationRelativeTo(null);
JWindow.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
JWindow.setResizable(false);
Font font = new Font("宋体", Font.PLAIN, 20);
JPanel Panel1 = new JPanel();
JPanel Panel2 = new JPanel(new GridLayout(4,4,8,12));
JTextArea JText = new JTextArea(1,16);
JText.setFont(font);
JText.setPreferredSize(new Dimension(300,30));
JText.setEditable(false);
Panel1.add(JText);
String BtnStr[] = { "1","2","3","+",
"4","5","6","-",
"7","8","9","x",
".","0","=","÷"};
JButton Btn[] = new JButton[BtnStr.length];
for(int i = 0 ; i < BtnStr.length ; i++ ){
Btn[i]=new JButton(BtnStr[i]);
Btn[i].setFont(font);
Dimension dimension = new Dimension(70,42);
Btn[i].setPreferredSize(dimension);
Panel2.add(Btn[i]);
}
JWindow.add(Panel1,BorderLayout.NORTH);
JWindow.add(Panel2,BorderLayout.CENTER);
JWindow.setVisible(true);
}
public static void main(String[] args) {
Calculator calculator = new Calculator();
}
}
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class NumberConverterGUI extends JFrame implements ActionListener {
private JLabel decimalLabel, binaryLabel, octalLabel, hexadecimalLabel;
private JTextField decimalField, binaryField, octalField, hexadecimalField;
private JButton convertButton;
public NumberConverterGUI() {
decimalLabel = new JLabel("Decimal:");
decimalField = new JTextField(10);
binaryLabel = new JLabel("Binary:");
binaryField = new JTextField(10);
octalLabel = new JLabel("Octal:");
octalField = new JTextField(10);
hexadecimalLabel = new JLabel("Hexadecimal:");
hexadecimalField = new JTextField(10);
convertButton = new JButton("Convert");
convertButton.addActionListener(this);
JPanel panel = new JPanel(new GridLayout(5, 2, 10, 10));
panel.add(decimalLabel);
panel.add(decimalField);
panel.add(binaryLabel);
panel.add(binaryField);
panel.add(octalLabel);
panel.add(octalField);
panel.add(hexadecimalLabel);
panel.add(hexadecimalField);
panel.add(new JLabel(""));
panel.add(convertButton);
setContentPane(panel);
setTitle("Number Converter");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
pack();
setLocationRelativeTo(null);
setVisible(true);
}
public void actionPerformed(ActionEvent e) {
int decimalNumber = Integer.parseInt(decimalField.getText());
String binaryNumber = Integer.toBinaryString(decimalNumber);
String octalNumber = Integer.toOctalString(decimalNumber);
String hexadecimalNumber = Integer.toHexString(decimalNumber);
binaryField.setText(binaryNumber);
octalField.setText(octalNumber);
hexadecimalField.setText(hexadecimalNumber);
}
public static void main(String[] args) {
new NumberConverterGUI();
}
}
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class ScoreChartInterface extends JFrame implements ActionListener {
private List<Double> scores;
private JLabel scoreLabel, resultLabel;
private JTextField scoreField;
private JButton addButton, calculateButton;
interface ScoringRule {
double calculateScore(List<Double> scores);
}
class AverageScoringRule implements ScoringRule {
@Override
public double calculateScore(List<Double> scores) {
double sum = 0;
for (double score : scores) {
sum += score;
}
return sum / scores.size();
}
}
class TrimmedAverageScoringRule implements ScoringRule {
@Override
public double calculateScore(List<Double> scores) {
if (scores.size() <= 2) {
throw new IllegalArgumentException("At least 3 scores are required for trimmed average scoring.");
}
List<Double> sortedScores = new ArrayList<>(scores);
Collections.sort(sortedScores);
double sum = 0;
for (int i = 1; i < sortedScores.size() - 1; i++) {
sum += sortedScores.get(i);
}
return sum / (scores.size() - 2);
}
}
public ScoreChartInterface() {
scores = new ArrayList<>();
scoreLabel = new JLabel("Score:");
scoreField = new JTextField(10);
addButton = new JButton("Add");
addButton.addActionListener(this);
resultLabel = new JLabel("Result: ");
calculateButton = new JButton("Calculate");
calculateButton.addActionListener(this);
JPanel panel = new JPanel(new GridLayout(4, 1, 10, 10));
panel.add(scoreLabel);
panel.add(scoreField);
panel.add(addButton);
panel.add(resultLabel);
panel.add(calculateButton);
setContentPane(panel);
setTitle("Score Chart");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
pack();
setLocationRelativeTo(null);
setVisible(true);
}
public void actionPerformed(ActionEvent e) {
if (e.getSource() == addButton) {
try {
double score = Double.parseDouble(scoreField.getText());
scores.add(score);
scoreField.setText("");
} catch (NumberFormatException ex) {
JOptionPane.showMessageDialog(this, "Invalid score format!", "Error", JOptionPane.ERROR_MESSAGE);
}
} else if (e.getSource() == calculateButton) {
if (scores.isEmpty()) {
JOptionPane.showMessageDialog(this, "No scores available!", "Error", JOptionPane.ERROR_MESSAGE);
return;
}
ScoringRule scoringRule = new AverageScoringRule();
double finalScore = scoringRule.calculateScore(scores);
resultLabel.setText("Result: " + finalScore);
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
new ScoreChartInterface();
});
}
}