用JAVA编写一个程序,输入汽车的品牌名和颜色,输出汽车的品牌名,颜色,和奔跑的速度
时间: 2023-07-16 17:14:15 浏览: 74
以下是一个简单的Java代码实现:
```java
import java.util.Scanner;
public class Car {
private String brand;
private String color;
private int speed;
public Car(String brand, String color) {
this.brand = brand;
this.color = color;
this.speed = 0;
}
public void run(int speed) {
this.speed = speed;
System.out.println("品牌:" + brand);
System.out.println("颜色:" + color);
System.out.println("速度:" + speed + "km/h");
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("请输入汽车品牌名:");
String brand = scanner.nextLine();
System.out.print("请输入汽车颜色:");
String color = scanner.nextLine();
Car car = new Car(brand, color);
System.out.print("请输入汽车奔跑的速度:");
int speed = scanner.nextInt();
car.run(speed);
}
}
```
在程序中,我们定义了一个 `Car` 类,它有三个属性:品牌名、颜色和速度。其中,品牌名和颜色在构造方法中传入,速度在 `run` 方法中设置。
在 `main` 方法中,我们先使用 `Scanner` 类获取用户输入的品牌名和颜色,然后创建一个 `Car` 对象。接着,我们再使用 `Scanner` 获取用户输入的速度,并调用 `run` 方法输出汽车的品牌名、颜色和速度。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)