2.用java定义一个Phone类,要求如下: 属性:品牌(brand)、价格(price) ; 方法:构造方法,setBrand、getBrand、getPrice和setPrice方法,其中setPrice(int price)若price<200,则抛出LessException,若price>20000,则抛出GreatException 。 编写自定义LessException和GreatException异常类。 编写Phone类。在setPrice方法体中抛出LessException或GreatException异常类 编写类ExceptionTest3:
时间: 2024-03-06 11:47:26 浏览: 134
好的,我来给您写一下代码:
首先定义LessException和GreatException异常类:
```java
class LessException extends Exception {
public LessException() {
super("价格低于200!");
}
}
class GreatException extends Exception {
public GreatException() {
super("价格高于20000!");
}
}
```
然后定义Phone类:
```java
class Phone {
private String brand;
private int price;
public Phone(String brand, int price) {
this.brand = brand;
this.price = price;
}
public String getBrand() {
return brand;
}
public void setBrand(String brand) {
this.brand = brand;
}
public int getPrice() {
return price;
}
public void setPrice(int price) throws LessException, GreatException {
if (price < 200) {
throw new LessException();
} else if (price > 20000) {
throw new GreatException();
} else {
this.price = price;
}
}
}
```
最后编写ExceptionTest3类:
```java
import java.util.Scanner;
public class ExceptionTest3 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("请输入手机品牌:");
String brand = scanner.nextLine();
System.out.print("请输入手机价格:");
int price = scanner.nextInt();
Phone phone = new Phone(brand, price);
try {
phone.setPrice(price);
} catch (LessException e) {
System.out.println(e.getMessage());
} catch (GreatException e) {
System.out.println(e.getMessage());
}
}
}
```
这样,当我们输入的价格小于200或大于20000时,就会抛出相应的异常。
阅读全文