java - 如何打印用户创建的现有配置文件?关于在用户创建的两个配置文件之间切换的任何提示?
问题描述
class Profiles
{
private Scanner sc;
private Profile[] profiles;
private int idx; // master index of profiles array
private int nop; //number of profiles
public Profiles()
{
sc = new Scanner(System.in);
idx = -1;
nop = 0;
profiles = new Profile[3];
}
public void createProfile(String first,String last,int age)
{
if(idx<profiles.length-1)
{
Profile p = new Profile(first,last,age);
idx++;
profiles[idx] = p;
nop++;
Util.print("Profile has been created\n");
}
else
{
Util.print("No room to create a new profile\n");
}
}
到目前为止,用户可以创建配置文件。但现在是我的问题...
public void switchProfile()
{
if(nop==0)
{
Util.print("Unable to switch profiles");
return;
}else
{
//print the idx and all profiles that currently exist <--not sure how to do this
//accept a profile idx that the user chooses (use Scanner to get user input)
//set idx to the input (this will direct the user to the profile idx they chose)
}
}
在 else 语句之后,我努力想出一种方法来打印存在的当前配置文件。
有任何想法吗?
解决方案
将问题分解为步骤。
- 打印带有索引的数组。
- 请求输入
- 处理输入
System.out.println("Pick a profile");
for (int i = 0; i < profiles.length; i++) {
System.out.printf("%d : %s\n", i, profiles[i].getName());
}
int next = Integer.parseInt(sc.nextLine());
if (next < profiles.length && next >= 0) {
idx = next;
} else {
// invalid index
}
但是,如果您在执行此操作后调用 add profile 方法,最终将覆盖数组中的数据
为避免这种情况,您需要仅将配置文件添加到数组中的空位置
推荐阅读
- twilio - 如何在 Twilio 运行时函数中录制电话会议?
- powershell - 奇怪的结果:很多空格而不是正确的句子 Powershell
- android - Android Studio 添加了@androidx.annotation 和@android.support.annotation 问题
- python - 使用一个“绘图”调用绘制多条曲线时的一个图例条目
- postgresql - 在 postgres 中合并
- angular - 导航到组件路由时出错
- arrays - 如何在数组中添加元素?
- c# - 如何修复“无法读取超出流末尾”的错误?
- javascript - .default 不是使用带有 javascript 包的声明文件的构造函数
- android - 房间数据库丢失数据