I am trying to do an assignment for class, but I have run into a problem that I cannot find the solution for. I have a variable in my main method called passwd. I have a user enter a possible password and that input is stored in the variable. I then check the length of the password variable to make sure it meets the length requirements. I want to then have another method chat checks each of the characters of the variable to see if it is a digit.
The problem is I cannot use the passwd variable from the main method in my digitCheck() method.
Can someone please advise me on how to solve this problem.
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++;
}
}
}
The problem in your case is because you are declaring the variable within different scopes. You have two options:
Either:
Move your variable to a Global Variable, you do this by declaring the variable outside a method, usually just under the class decleration, in your case this could be just above or below
private static Component frame;.Pass your variable as a parameter to the other method, so you would need to change your
digitCheck()method todigitCheck(String passwd)and then call it like so:digitCheck(passwd).The first option will allow you access the variable from what ever section of your class you are into. On the other hand, the second option will allow you to easier re-use the method you have created since the method will be self contained, not relying on the usage of global variables.