【问题标题】:How to return multiple string values from a method java [duplicate]如何从方法java返回多个字符串值[重复]
【发布时间】:2019-10-21 17:50:18
【问题描述】:

我无法同时返回用户名和传递String 值。

    public static String executeLogin(String username, String pass) {
        int totalAttempts = 5;

        if (totalAttempts != 0) {
            if (username == "Javaprogram" && (pass == "Legend1@")) {
                System.out.println("Correct");
            } else {
                System.out.println("Incorrect Login");
                totalAttempts--;
            }
            if (totalAttempts == 0) {
                System.out.println("Maximum number of attempts exceeded");  
            }

        }
        return "username,pass";                 
    }

【问题讨论】:

  • 与你的问题无关,这不是你compare strings in java的方式。
  • 一个方法不能返回多个值(除非该方法被多次调用)。
  • 这在 java 中是不可能的。而是创建一个对象(比如说Credentials),它包含两个值并返回所述对象的实例。
  • 另外,我想不出任何逻辑上的理由,你会想要返回用户名并传递......你正在将它们传递给方法......因此你已经在调用者中有它们?跨度>
  • Object 的子类或数组[]

标签: java string methods


【解决方案1】:

注意:您的“总尝试次数”变量应该在函数范围之外!

你可以返回一个字符串列表:

static int totalAttempts = 5;

public static String[] executeLogin(String username, String pass) {

    if (totalAttempts != 0) {
        if (username == "Javaprogram" && (pass == "Legend1@")) {
            System.out.println("Correct");
        } else {
            System.out.println("Incorrect Login");
            totalAttempts--;
        }
        if (totalAttempts == 0) {
            System.out.println("Maximum number of attempts exceeded");
        }

    }

    return new String[]{username, pass};
}

【讨论】:

  • 为什么不创建一个 Credentials 类并采用 OOP 方式。否则用户必须处理数组的实际大小,可能是空的,也可能只有一三个条目,谁知道呢。这很容易出错。
  • 我正在尝试将用户名和密码从 main 方法传递到 executelogin 方法。如何做到这一点?
猜你喜欢
  • 2012-09-20
  • 2020-01-22
  • 2018-02-24
  • 1970-01-01
  • 2016-05-19
  • 1970-01-01
  • 1970-01-01
  • 2021-01-14
  • 2015-03-04
相关资源
最近更新 更多