首页 > 解决方案 > 如何打印用户创建的现有配置文件?关于在用户创建的两个配置文件之间切换的任何提示?

问题描述

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 语句之后,我努力想出一种方法来打印存在的当前配置文件。

有任何想法吗?

标签: javaarrays

解决方案


将问题分解为步骤。

  • 打印带有索引的数组。
  • 请求输入
  • 处理输入

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 方法,最终将覆盖数组中的数据

为避免这种情况,您需要仅将配置文件添加到数组中的空位置


推荐阅读