这段代码怎么修改可以主动录入
时间: 2024-02-23 10:00:25 浏览: 147
要实现主动录入,可以在主函数中添加一个循环,让用户不断输入衣物信息并添加到衣柜中。你可以按照以下步骤修改代码:
1. 在`main`方法中添加一个循环,让用户可以不断输入衣物信息:
```
Scanner scanner = new Scanner(System.in);
while (true) {
System.out.println("请输入衣物名称(输入exit退出):");
String name = scanner.nextLine();
if ("exit".equals(name)) {
break;
}
System.out.println("请输入衣物颜色:");
String color = scanner.nextLine();
System.out.println("请输入衣物尺码:");
int size = scanner.nextInt();
scanner.nextLine(); // 读取换行符
clothes newClothes = new clothes(name, color, size);
wardrobe.addClothes(newClothes);
}
```
2. 在循环中,先让用户输入衣物名称,如果用户输入`exit`则退出循环;否则让用户输入衣物颜色和尺码,然后创建一个新的衣物对象并添加到衣柜中。
完整代码如下:
```
import java.util.ArrayList;
import java.util.Scanner;
class clothes {
String name;
String color;
int size;
public clothes(String name, String color, int size) {
this.name = name;
this.color = color;
this.size = size;
}
}
class Wardrobe {
private ArrayList<clothes> clothesList = new ArrayList<>();
public void addClothes(clothes clothes) {
clothesList.add(clothes);
}
}
public class Main {
public static void main(String[] args) {
Wardrobe wardrobe = new Wardrobe();
Scanner scanner = new Scanner(System.in);
while (true) {
System.out.println("请输入衣物名称(输入exit退出):");
String name = scanner.nextLine();
if ("exit".equals(name)) {
break;
}
System.out.println("请输入衣物颜色:");
String color = scanner.nextLine();
System.out.println("请输入衣物尺码:");
int size = scanner.nextInt();
scanner.nextLine(); // 读取换行符
clothes newClothes = new clothes(name, color, size);
wardrobe.addClothes(newClothes);
}
}
}
```
这样就可以主动录入衣物信息并添加到衣柜中了。
阅读全文
相关推荐













