编写一个java程序,允许用户在键盘上输入若干数字,程序将计算出这些数字的和以及平均值。当输入的数字大于100或小于0时,程序将产生异常对象。编写一个测试类程序,对其进行测试。
时间: 2024-10-21 15:02:05 浏览: 36
java实验:编写一个java应用程序,用户从键盘输入一个1-99999的数,程序将判断这个数是几位数,并判断这个数是.pdf
在Java中,你可以创建一个简单的控制台应用程序来完成这个任务。首先,我们需要定义一个`NumberCalculator`类来处理用户的输入和计算:
```java
import java.util.Scanner;
public class NumberCalculator {
private double sum = 0;
private int count = 0;
public void addNumber(double number) {
if (number > 100 || number < 0) {
throw new IllegalArgumentException("Input must be between 0 and 100");
}
sum += number;
count++;
}
public double getSum() {
return sum;
}
public double getAverage() {
return count > 0 ? sum / count : 0; // 如果没有数字,返回0作为平均值
}
}
```
接下来,我们可以编写一个`Main`类来获取用户输入并测试`NumberCalculator`:
```java
public class Main {
public static void main(String[] args) {
NumberCalculator calculator = new NumberCalculator();
Scanner scanner = new Scanner(System.in);
System.out.println("Enter numbers (type 'end' to finish):");
while (true) {
try {
String input = scanner.nextLine();
if (input.equalsIgnoreCase("end")) break;
double num = Double.parseDouble(input);
calculator.addNumber(num);
} catch (NumberFormatException e) {
System.out.println("Invalid input. Please enter a number.");
continue;
} catch (IllegalArgumentException e) {
System.out.println(e.getMessage());
}
}
double sum = calculator.getSum();
double average = calculator.getAverage();
System.out.printf("Sum: %.2f%n", sum);
System.out.printf("Average: %.2f%n", average);
}
}
```
现在,我们创建一个测试类来验证`NumberCalculator`的行为:
```java
import org.junit.jupiter.api.Test;
public class NumberCalculatorTest {
@Test
public void testValidNumbers() {
NumberCalculator calculator = new NumberCalculator();
calculator.addNumber(50);
calculator.addNumber(75);
assertDoubleEqual(calculator.getSum(), 125);
assertDoubleEqual(calculator.getAverage(), 62.5);
}
@Test
public void testExceptionHandling() {
NumberCalculator calculator = new NumberCalculator();
try {
calculator.addNumber(-50); // expecting an exception
fail("Expected IllegalArgumentException but no exception was thrown");
} catch (IllegalArgumentException e) {
assertEquals("Input must be between 0 and 100", e.getMessage());
}
}
private void assertDoubleEqual(double expected, double actual) {
double epsilon = 0.0001;
assertEquals(expected, actual, epsilon);
}
}
```
在这个测试类中,`testValidNumbers`确保正常输入会被正确处理,而`testExceptionHandling`检查了异常是否按预期被捕获。
阅读全文