Browse Source

上传文件至 'w6'

main
Chengwuyi 3 weeks ago
parent
commit
0d4b743d88
  1. 11
      w6/Animal.java
  2. 22
      w6/AnimalTest.java
  3. 13
      w6/Cat.java
  4. 18
      w6/Dog.java
  5. 45
      w6/ScoreReader.js

11
w6/Animal.java

@ -0,0 +1,11 @@
package org.example;
public abstract class Animal {
String name;
public Animal(String name) {
this.name = name;
}
public abstract void makeSound();
}

22
w6/AnimalTest.java

@ -0,0 +1,22 @@
package org.example;
public class AnimalTest {
public static void main(String[] args) {
Animal dog = new Dog("Buddy");
Animal cat = new Cat("Kitty");
dog.makeSound();
cat.makeSound();
if (dog instanceof Swimmable) {
((Swimmable) dog).swim();
}
if (cat instanceof Swimmable) {
((Swimmable) cat).swim();
} else {
System.out.println(cat.name + " cannot swim.");
}
}
}

13
w6/Cat.java

@ -0,0 +1,13 @@
package org.example;
public class Cat extends Animal {
public Cat(String name) {
super(name);
}
@Override
public void makeSound() {
System.out.println(name + " says: Meow!");
}
}

18
w6/Dog.java

@ -0,0 +1,18 @@
package org.example;
public class Dog extends Animal implements Swimmable {
public Dog(String name) {
super(name);
}
@Override
public void makeSound() {
System.out.println(name + " says: Woof!");
}
@Override
public void swim() {
System.out.println(name + " is swimming!");
}
}

45
w6/ScoreReader.js

@ -0,0 +1,45 @@
package org.example;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
public class ScoreReader {
public static void main(String[] args) {
int sum = 0;
int count = 0;
// try-with-resources:自动关闭流,不需要手动 br.close()
try (BufferedReader br = new BufferedReader(new FileReader("scores.txt"))) {
String line;
while ((line = br.readLine()) != null) {
try {
sum += Integer.parseInt(line.trim());
count++;
} catch (NumberFormatException e) {
// 处理数字格式错误
System.out.println("跳过无效数据:" + line);
}
}
if (count > 0) {
double average = (double) sum / count;
System.out.println("总分:" + sum);
System.out.println("人数:" + count);
System.out.printf("平均分:%.2f%n", average);
} else {
System.out.println("文件中没有有效成绩。");
}
} catch (FileNotFoundException e) {
// 处理文件不存在
System.out.println("错误:找不到文件 scores.txt,请检查路径。");
} catch (IOException e) {
// 处理读取错误
System.out.println("错误:读取文件时发生异常:" + e.getMessage());
}
}
}
Loading…
Cancel
Save