如何在其他方法中使用main方法的变量(用户输入)?

Cur*_*ore 0 java variables methods

我正在尝试为课程做一个作业,但我遇到了一个我无法找到解决方案的问题.我的main方法中有一个名为passwd的变量.我有一个用户输入一个可能的密码,该输入存储在变量中.然后我检查密码变量的长度,以确保它满足长度要求.我想有另一个方法聊天检查变量的每个字符,看看它是否是一个数字.

问题是我无法在我的digitCheck()方法中使用main方法中的passwd变量.

有人可以告诉我如何解决这个问题.

 package Password;

import java.awt.Component;
import javax.swing.JOptionPane;

/**
 *
 * @author Curtis
 */
public class Password 
{
private static Component frame;

//Main Method
public static void main(String[] args) 
{//Declaration of variables
    String passwd;
    int leng;
    boolean length = false;
    //Prompt user to enter possible password
    while(!length)
    {
        passwd = JOptionPane.showInputDialog("Please enter a possible password:\n" +  
            "Password must contain 6-10 characters\n"+
            "Password must contain both a letter and a digit");
        leng =passwd.length();//Determines Password Length
        if(leng>5 && leng<11)
            { 
                length = true;
                digitCheck();
            }
        else //Gives Password Length Error Message
        {
            length = false;
            JOptionPane.showMessageDialog(frame, "Your password does not meet the length requirements.", "Password Length Error", JOptionPane.ERROR_MESSAGE); 
        }
    }
}
//Digit Check Method
public static void digitCheck();
{// declaration of variables
    char c;
    int digits = 0;
    for(int i=0;i<leng;i++)
    {
        c = passwd.charAt(i);
        if(Character.isDigit(c))
            digits++;
    }

}

}
Run Code Online (Sandbox Code Playgroud)

NPE*_*NPE 5

最直接的方法是passwd作为参数传递给digitCheck():

public static void main(String[] args) {
            ...
            length = true;
            digitCheck(passwd);
            ...
}

public static void digitCheck(String passwd) {
   // use passwd here
   ...
}
Run Code Online (Sandbox Code Playgroud)

请注意,leng也无法访问.由于您可以通过调用找出字符串的长度passwd.lenth(),因此无需leng作为单独的参数传递.