【问题标题】:changing String value based upon String[] index根据 String[] 索引更改字符串值
【发布时间】:2020-01-14 22:20:40
【问题描述】:

我知道怎么做

public class AccountPicker {

    public static void main(String[] args) throws InterruptedException {
        String password = "";
        String[] accounts = {"a", "b", "c"};

        Random r = new Random();
        int assigned = r.nextInt(3);

        if (assigned == 2) {
            password = "password";
            System.out.println("account: " + accounts[assigned] + " " + "password: " + password);
        }

        if (assigned == 1) {
            password = "Password";
            System.out.println("account: " + accounts[assigned] + " " + "password: " + password);
        }

        if (assigned == 0) {
            password = "PASSWORD";
            System.out.println("account: " + accounts[assigned] + " " + "password: " + password);
        }
    }
}

基本上这是在选择一个帐户a, b , or c 并根据从accounts 中挑选出的索引来更改password

但是如果我在accounts 中有 100 个值呢?

制作 100 个 if 语句会占用太多代码..

有没有更有效的方法?

【问题讨论】:

    标签: java arrays string random


    【解决方案1】:

    您可以创建一个与每个帐户对应的密码数组,例如:

    import java.util.Random;
    
    public class AccountPicker {
    
        public static void main(String[] args) throws InterruptedException {
    
            String password = "";
            String[] accounts = { "a", "b", "c" };
            String[] passwords = { "password", "Password", "PASSWORD" };
    
            Random r = new Random();
            int assigned = r.nextInt(3);
    
            System.out.println("account: " + accounts[assigned] + ", password: " + passwords[assigned]);
        }
    }
    

    示例运行:

    account: c, password: PASSWORD
    

    【讨论】:

      【解决方案2】:

      此任务特别适合Map。所以你也可以这样做。

          Map<String,String> accts = Map.of("a","password", "b", "Password", "c", "PASSWORD");
          System.out.println(accts.get("c"));
      

      打印

      密码

      要查看所有内容,您可以通过多种方式进行。

      accts.forEach(System.out::println);
      

      accts.forEach(e->System.out.println(e.getKey() + " " e.getValue());
      

      他们只提供帐户(或用户名),而不是给你一个号码。但请选择最适合您的。

      【讨论】:

        【解决方案3】:

        您基本上是将数字映射到字符串。您可以创建一个字符串数组,可以是硬编码的,也可以是从其他地方获得的,然后在该数组中选择一个随机值。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2022-08-09
          • 1970-01-01
          • 2019-12-22
          • 1970-01-01
          • 1970-01-01
          • 2019-04-06
          • 1970-01-01
          相关资源
          最近更新 更多