【问题标题】:How do I call a method inside another class from my main? [duplicate]如何从我的 main 调用另一个类中的方法? [复制]
【发布时间】:2014-11-06 12:07:24
【问题描述】:

我这里有一些代码应该要求用户输入将在我的第二堂课中检查的“密码”。我的问题是程序不会传递到我的第二类(PasswordChecker)中的方法,我将如何解决这个问题?我认为这与这条线有关:

blnPassword2 = PasswordChecker.PasswordCheck(PasswordGuess);

import java.util.Scanner;

public class PasswordGuesser {

    public static void main(String[] args){
        boolean blnPassword2;
        Scanner keyboard = new Scanner(System.in);
        String PasswordGuess = keyboard.nextLine();
        blnPassword2 = PasswordChecker.PasswordCheck(PasswordGuess);

        if (blnPassword2==true) {
            System.out.println("Password correct");
        }
        else 
            {
            System.out.println("Password incorrect");
        }
    }
}    

public class PasswordChecker {

    public static boolean PasswordCheck(String PasswordGuess){
        boolean blnPassword;
        String StrPassword = "Enter";

        if (PasswordGuess==StrPassword) {
            blnPassword = true;
        }
        else {
            blnPassword = false;
        }
        return (blnPassword);
    }
}

谢谢,

杰森·雷恩

【问题讨论】:

  • 你遇到了什么错误?
  • 在 if 中使用 PasswordGuess.equals(StrPassword) 而不是 ==。

标签: java parameter-passing method-call


【解决方案1】:

您正在比较对象的参考位置,而不是值。比较对象不同于比较原始数据类型(int、long、short、char)。

更改以下内容:

if(PasswordGuess==StrPassword)

if(PasswordGuess.equals(StrPassword))

请在此处阅读有关执行相等操作的内容:

http://perso.ensta-paristech.fr/~diam/java/online/notes-java/data/expressions/22compareobjects.html

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-10-08
    • 2015-08-08
    • 2011-06-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-27
    • 2012-11-19
    相关资源
    最近更新 更多