So I have to write a program that prompts the user to enter a password that has to follow three requirements: at least 8 characters long, only letters and digits, and at least two digits. Now the method I created to check these three requirements I believe is sound, but my program also has to do some exception handling and be able to ask the user to reenter the password if one of the requirements is off and display the respective error message to go along with each requirement. I created a string errorMessage to relay that message but it gives me an error when i try to call it in my main ?
My other issue is that the password must be taken in to my program by using JPasswordField but I am struggling with even setting it up because of the numerous other factors like the JPanel, buttons, and action events that I read has to go along with it. I attempted to use JPasswordField and noticed that the line that takes in the password, takes it in as an array, when my checkPassword method needs a string, how can i take in that password as a string instead?
This is what I have for my program so far:
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPasswordField;
import javafx.event.ActionEvent;
public class Ed10Chp6Ex6Point18CheckPasswordProgram {
public static void main(String[] args) {
final JFrame frame = new JFrame("Check Password Program");
JLabel jlbPassword = new JLabel("Please enter the password: ");
JPasswordField jpwName = new JPasswordField(15);
jpwName.setEchoChar('*');
jpwName.addActionListener(new ActionListener()) {
public void actionPerformed(ActionEvent e) {
JPasswordField input = (JPasswordField) e.getSource();
char[] password = input.getPassword();
if(checkPassword(password)){
JOptionPane.showMessageDialog(frame, "Congradulations, your password follows all the requirements");
}
else{
JOptionPane.showMessageDialog(frame, errorMessage);
}
}
}
}
public static boolean checkPassword(String x) {
String errorMessage = "";
//must have at least eight characters
if (x.length() < 8){
errorMessage = "The password you entered is invalid, password must be at least 8 characters";
return false;
}
//consists of only letters and digits
for (int i = 0; i < x.length(); i++) {
if (!Character.isLetter(x.charAt(i)) && !Character.isDigit(x.charAt(i))) {
errorMessage = "The password you entered is invalid, password must contain only letters and digits";
return false;
}
}
//must contain at least two digits
int count = 0;
for (int i = 0; i < x.length(); i++) {
if (Character.isDigit(x.charAt(i))){
count++;
}
}
if (count >= 2){
return true;
}
else {
errorMessage = "The password you entered is invalid, password must contain at least two digits";
return false;
}
}
}
I apologize in advanced in case some of my questions seem rudimentary, any help would be greatly appreciated, thank you!
Two things right off the bat:
(1) Make sure you are importing the correct classes, don't rely on an IDE to do proper imports. You are importing the ActionEvent class from JavaFX, but the framework you are working with is Swing.
Change
import javafx.event.ActionEvent;
To
import java.awt.event.ActionEvent;
I am not very familiar with how nicely JavaFX and Swing play with one another, but using the correct classes typically helps avoid headaches and compile/runtime errors.
(2) A static method in the java.lang.String class provides a convenient way to convert a char array into a string. In your actionPerformed method, add this:
String passStr = String.valueOf(password);
E.g.
#Override
public void actionPerformed(ActionEvent e) {
// Get the source of the event, we know it is a JPasswordField so we cast it.
JPasswordField input = (JPasswordField) e.getSource();
// Get the char array from the input the user typed stored in the input object.
char[] password = input.getPassword();
// Convert char[] to String
String passwordStr = String.valueOf(password);
if(checkPassword(passwordStr)){
JOptionPane.showMessageDialog(frame, "Congradulations, your password follows all the requirements");
} else {
JOptionPane.showMessageDialog(frame, errorMessage);
}
}
how can i take in that password as a string instead
Either checkPassword(new String(input.getPassword)) or update your method to accept a char[] instead of a String.
As for error checking, you should use throw new ShortPasswordException(), where you want to throw that error, after you implement a class like ShortPasswordException extends Exception, for example.
Then, you can do
try {
checkPassword();
} catch (ShortPasswordException e) {
// TODO: Handle exception
}
Tip for the more adventurous: Use a regular expression to check your password requirements. A match of \d{2}, for example, means you have 2 consecutive digits.
Related
Basically i want to enter the names as long as i don't cancel the InputMessageDialog, then i want to asign my names to variable created before and print them out at the end in the MessageDialog. I was trying some stuff outside the loop but got the notificacion that "value 'names' is always 'null'"
String names;
while (true) {
names = JOptionPane.showInputDialog(null, "ENTER THE NAMES");
if (names == null) {
JOptionPane.showMessageDialog(null, "ENTRY CANCELED!");
break;
} else {
}
}
JOptionPane.showMessageDialog(null, "YOUR NAMES: " + names);
Your code is pretty close to what you describe as your goal – the primary thing missing is that you need to keep track of the various values along the way, and print them at the end.
The code you posted will loop again and again asking for a single value (which you are storing into String names - a little confusing choice for variable name, since it contains only one name input). As you found, when the user hits the cancel button (to end the loop), it sets names to null. The final step shows a dialog box with the last value for names (which is always null).
Here's a program that:
loops until the user hits the "cancel" button (which would set input to be null), or if they enter a blank value – this allows the user to exit by simply hitting return without typing anything
adds all non-empty input values to a java.util.Set – this is an arbitrary choice, use whatever data structure is appropriate for your program
shows a final dialog with the contents of the set
import javax.swing.*;
import java.util.HashSet;
import java.util.Set;
public class t {
public static void main(String[] args) {
Set<String> values = new HashSet<>();
while (true) {
String input = JOptionPane.showInputDialog(null, "enter something");
if (input != null && !input.isEmpty()) {
values.add(input);
} else {
break;
}
}
JOptionPane.showMessageDialog(null, "all values: " + values);
}
}
If I run with the following input:
one
two two
three three three
<blank>
Then the final dialog message is:
all values: [one, two two, three three three]
Note that a java.util.Set doesn't necessarily return items in any specific order, it just happens to have worked out that way in this example.
I am a new programmer in bluej. i tried using JPasswordField to accept a password .I added a button to submit the password. The problem is that nothing gets displayed even when the password is right or wrong.
I changed my code slightly to find the problem. I added an error message at the end. I added a check for equal length and equal characters in the final else . i added a message to be displayed when the button is pressed. i saved the sample password in the program itself in the form of a char[] .I made nearly all the variable into static fields(so that they could be accessed by the object from outside).I even wrote the code for the ActionListener actionPerformed() methodoutside the main method.
This is my code.Sorry for pasting it entirely I couldn't identify the problematic part.
hint:You may overlook the parts I made for debugging(see above)
import java.util.*;
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
class superb
{static char m[]={'h','i'};
static char z[]={' '};
static int w=0;
static char check;
static JButton j=new JButton("click me");
static JPasswordField n=new JPasswordField();
public static void main()
{Frame f=new Frame("hi");
f.setVisible(true);
f.setLayout(null);
f.add(n);
n.setBounds(100,200,100,200);
f.setSize(500,1000);
f.add(j);
j.setBounds(250,500,100,200);
j.setActionCommand("Sucesss");
j.addActionListener(abs);
j.setIcon(new ImageIcon("images1"));
System.out.println(z);
}
static ActionListener abs=new ActionListener()
{
public void actionPerformed(ActionEvent E){
String a=E.getActionCommand();
if(a.equals("Sucesss") )
{
System.out.println("button pressed");
z=n.getPassword();
if(z.equals(m))
{JOptionPane.showMessageDialog(null,"Sucessful");
System.out.println("sucess button");
}
}
else
{
if(z.length==m.length)
{System.out.println("Equal length");
for(char c:z)
{check= c;
if(c==m[w])
{w++;}
}
if(w==z.length)
{
System.out.println("Same Characters");
System.out.println("error");
}
else
System.out.println("different characters");
}
else{JOptionPane.showMessageDialog(null,"Unequal length");
}
}
}
};
}
The problematic part I think might be the action listener
public void actionPerformed(ActionEvent E){
String a=E.getActionCommand();
if(a.equals("Sucesss") )
{
System.out.println("button pressed");
z=n.getPassword();
if(z.equals(m))
{JOptionPane.showMessageDialog(null,"Sucessful");
System.out.println("sucess button");
}
}
else
{
if(z.length==m.length)
{System.out.println("Equal length");
for(char c:z)
{check= c;
if(c==m[w])
{w++;}
}
if(w==z.length)
{
System.out.println("Same Characters");
System.out.println("error");
}
else
System.out.println("different characters");
}
else{JOptionPane.showMessageDialog(null,"Unequal length");
}
}
}
};
m is the sample password
z is the accepted password
w is the variable that checks the password
The expected output should be
System console
button pressed
success button
![password field and button]
the actual output is
System console
button pressed
![password field and button]
The issue is because you are trying to compare two objects that are arrays of characters. You might better use
if (Arrays.equals(z, m)) ...
Documentation says:
public static boolean equals(char[] a,
char[] a2)
Returns true if the two specified arrays of chars are equal to one
another. Two arrays are considered equal if both arrays contain the
same number of elements, and all corresponding pairs of elements in
the two arrays are equal. In other words, two arrays are equal if they
contain the same elements in the same order. Also, two array
references are considered equal if both are null.
How can I make a JTextfield accept only Hebrew letters with if statement?
I can do a long if statement with all the Hebrew letters but it will not look good.
I found out that the Unicode of Hebrew first letter is \u05D0 and last one is \u05EA.
How can I say that if the gettext is in between these 2 letters so show (meaning to check if the text entered is only a Hebrew letter), the user will add only one letter in each textfield.
Thank you in advance
Build an input validator with your validation logic, and attach it to your textField to verify input as you enter it. Steps: Combine the validation logic given by #peter-lawray with the mechanism of building an input verifier and you're good to go.
You could use a simple one-liner using a Stream
boolean valid = jTextField.getText().chars().allMatch(p -> p <= 0x05ea && p >= 0x05d0);
Putting the other answers together, this is an input validator you could use:
// adapted from mohsenmadi/Daniel Rikowski
public class HebrewVerifier extends InputVerifier {
#Override
public boolean verify(JComponent input) {
String text = ((JTextField) input).getText();
// method suggested by Mad Matts
return text.chars().allMatch(p -> p <= 0x05ea && p >= 0x05d0);
}
}
And then you simply need to attach it to your JTextField:
myHebrewTextField.setInputVerifier(new HebrewVerifier());
Since you are using JTextField and this class inherits getText() method which returns a String. So, this is how I will probably do it.
String name = jTextField.getText();
char[] charArray = name.toCharArray();
for (char c : charArray) {
if (!(c <= 0x05ea && c >= 0x05d0)) {
break;
//valid
}
}
This can become more efficient, if you keep the counter of elements added/removed, you only will have to check the latest entered character (in case of removal you probably won't need that but that scenario will need more coding, so I hope you will figure that out once you solves this issue).
Update:
This is what I have tried:
String name = "אבגa";
char[] charArray = name.toCharArray();
for (char c : charArray) {
if (c <= 0x05ea && c >= 0x05d0) {
System.out.println("Valid hebrew");
}
}
And this prints Valid hebrew three times.
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.logging.Level;
import java.util.logging.Logger;
//...
public static String readHebrewString()
{
String str="";
System.out.println("הקלד שורה");
InputStreamReader in;
try {
char[]buffer=new char[1024];
in = new InputStreamReader(System.in, "Windows-1255");
in.read(buffer);
int i=0;
while((int)buffer[i]!=10)
str+=buffer[i++];
} catch (UnsupportedEncodingException ex) {
Logger.getLogger(Demo001.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(Demo001.class.getName()).log(Level.SEVERE, null, ex);
}
return str;
}
I want to create an application that asks the user to enter password from input dialogs.The password must be less than 10 characters and more than 6 characters.Also,the password should contain at least one digit or letter. When the password meets all the requirements,ask user to enter password again and do not let the user continue until the second password matches the first one.
My code is as follows but it is not checking the letter or digit.
Can anyone help?
import javax.swing.*;
import java.awt.*;
import java.util.Scanner;
public class Password{
public static void main(String[] args){
String firstPassword="";
String secondPassword="";
char charChecked;
boolean letter = false;
boolean digit = false;
int len=firstPassword.length();
firstPassword= JOptionPane.showInputDialog("ENter");
if (( len<6 || len>10) || ! (Character.isLetterOrDigit(firstPassword.charAt(len))) )
{firstPassword= JOptionPane.showInputDialog("Enter the Correct Format of password");
}
if ((len>=6|| len<=10) || (Character.isLetterOrDigit(firstPassword.charAt(len))) )
do
{
secondPassword= JOptionPane.showInputDialog("Please enter again the password to confirm");
}
while (!(firstPassword.equals(secondPassword)));
if (firstPassword.equals(secondPassword))
{
JOptionPane.showMessageDialog(null,"Accepted");
}
}
}
int len=firstPassword.length();
firstPassword= JOptionPane.showInputDialog("ENter");
your code are inverted... you need to call the length after input something.
firstPassword= JOptionPane.showInputDialog("ENter");
int len=firstPassword.length();
Try and say something...
I am trying to make code with a GUI that allows the user to enter a word in the JTextField and then have it check if it's a palindrome (i.e Ono is a palindrome, it is the same back and forth). How would I take the JTextField and convert them into chars to check if the sentence is a palindrome? (and also, how would I remove the spaces, punctuation, etc?) This is my current code set up
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.Stack;
/**
* Write a description of class Palidromania_Kevin here.
*
* #author Kevin Hy
* #version 09/23/13
*/
public class Palindromania extends JFrame
{
public JPanel panel1,panel2;
public JLabel main1;
public JButton check;
public JTextField enterPal;
public String inputWord,letter;
public int num;
public char checker;
public Stack<String> stack = new Stack<String>();
public Palindromania ()
{
super ("Palindromania Checker");
setSize (1024,768);
Container container = getContentPane();
panel1 = new JPanel();
panel1.setBackground (new Color(10,50,50));
panel1.setLayout (new FlowLayout());
panel2 = new JPanel();
panel2.setBackground (new Color(255,255,255));
panel2.setLayout (new FlowLayout());
main1 = new JLabel ("Palindromania Checker");
check = new JButton("Verify Palindrome");
ButtonHandler handler = new ButtonHandler();
check.addActionListener(handler);
enterPal = new JTextField(8);
container.add(panel1,BorderLayout.NORTH);
container.add(panel2,BorderLayout.CENTER);
panel2.add(enterPal);
panel2.add(check);
setVisible(true);
}
public static void main (String [] args)
{
Palindromania application = new Palindromania ();
}
public class ButtonHandler implements ActionListener
{
public void actionPerformed (ActionEvent event)
{
if (event.getSource () == check)//Check if palindrome button
{
inputWord="";letter="";
inputWord=enterPal.getText();
inputWord=inputWord.toLowerCase();
inputWord=inputWord.replace("[ !'-,]","");
for (int x=0; x<=inputWord.length()-1;++x)//inputs lettes into the stack
{
checker=inputWord.charAt(x);
letter+=checker;
stack.add(letter);
letter="";
JOptionPane.showMessageDialog (null, stack.peek());
}
for (int x=0; x<=inputWord.length()-1;++x)//inputs lettes into the stack
{
checker=inputWord.charAt(x);
letter+=checker;
stack.add(letter);
if (letter.equals(stack.pop()))
num+=1;
letter="";
}
if (num==inputWord.length())
JOptionPane.showMessageDialog (null, "You have a palindrome!");
else
JOptionPane.showMessageDialog (null, "This is not a palindrome, sorry!");
}
}
}
}EDIT: I modified back the code, made a mistake with the parse strings, and I can get the char letters to go in a test, and I can get the words that appear to go into the char and be outputted
EDIT2: So My main issue now, even though I can add stuff into the stack, is how come my .replace/.tolowercase on the string don't do anything? The strings I enter in the TextField do not get replaced (I.e HELLO WORLD stays as HELLO WORLD, not helloworld), and there is always a null in my stack, even though it is taking letters from inputWord? (i.e HELLO would be nullOLLEH) I also tried to put it into a string
compare+=stack.pop();
But all that does is it adds the letters with null to each? (nullnullO, nullOL nullOLL) Why does it have a null?
EDIT3: It works! A bit tedious the way I had to do it because I have to use a stack to compare (for the learning purposes)
There are a few mistakes in your code :
First your toUpperCase() doesn't work because you need to assign the result of this call back to the variable. So replace this : inputWord.toLowerCase(); by this : inputWord = inputWord.toLowerCase();. This comes from String being immutable in Java.
You can also simplify your code by using a simple regex. Use inputWord.replace("[ !',-]",""); instead of all your calls to replace and again assign the result to the variable. Like this : inputWord = inputWord.replace("[ !',-]","");
Now you have a null because you never initialize your letter String. Just add a little letter="" before your loop and the null should be gone.
And at the end just use pop() on the stack to get the reversed string just after the loop and compare it to the original one. Just like this :
if(inputWord.equalsIgnoreCase(stack.pop())){
JOptionPane.showConfirmDialog(null, "This is a Palindrome", "Is this a palindrome ?", JOptionPane.YES_OPTION, JOptionPane.INFORMATION_MESSAGE);
}
else {
JOptionPane.showConfirmDialog(null, "This is NOT a Palindrome", "Is this a palindrome ?", JOptionPane.YES_OPTION,JOptionPane.ERROR_MESSAGE);
}