String comparison for button events - java

I have a String named updatedDisplay that is set to empty in the constructor.
The buttons[] are JButtons and alarmCode is a String field.
I want the user to press four buttons (and they should be concatenated and stored in the updatedDisplay field).
The checkCode() method is executed to try match updatedDisplay against alarmCode. Trouble is, they never match. I think it may be something to do with a "space" when I originally declare my updatedDisplay as follows:
private String updatedDisplay = " ";
The updatedDisplay field doesn't seem to be storing the e.getActionCommand() value.
//add actionListeners to each button (except the "clear" button) to display value on screen
for (int i = 0; i< (buttons.length -1); i++) {
buttons[i].addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
//store the name of the button in a local variable
String command = e.getActionCommand();
System.out.println("You clicked " + command);
updatedDisplay = updatedDisplay + command;
//updatedDisplay = command;
System.out.println (updatedDisplay);
screen.setText(updatedDisplay);
}
});}
I have an armButton that, when pressed, should trigger the checkCode() method. The method checks if updatedDisplay and alarmCode are equal:
//add actionListener to the arm button
armButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
checkCode();
}
});
checkCode():
public void checkCode() {
//check if user entered the correct code
if (updatedDisplay == alarmCode)
{
updatedDisplay = "System Armed!";
screen.setText(updatedDisplay);
}
else
{
updatedDisplay = "Incorrect Code, Try again!";
screen.setText(updatedDisplay);
}
}
Even when I output the button presses to the terminal window they look right - but as I said, I suspect a "space" is being entered at the start.
Any ideas?

Solution
Try:
if( updatedDisplay.equals( alarmCode ) { // ...
Comparison
To understand this, read:
http://leepoint.net/notes-java/data/expressions/22compareobjects.html
Summary
Since updatedDate and alarmCode are object references, you must ask the objects to compare their values. You can think of them as pointers whose values are locations in memory that contain strings. Rather than comparing the value of the pointers (references), you want to compare the text that starts at that memory location.

Related

nothing is displayed even where there is a password in the password field and the button is pressed

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.

Testing whether an input is a number

I have a program, that whenever you type something and hit enter, it prints it out in a window (it's basically a command prompt). However, due to a few problems with a calculator function I'm trying to add, if the user input is a number, I want it to totally ignore it
input = new JTextField();
input.setEditable(true);
input.setForeground(Color.WHITE);
input.setCaretColor(Color.WHITE);
input.setOpaque(false);
input.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
String text = input.getText();
if (text.length() >= 1){
print(text + "\n", false);
doCommand(text);
scrollBottom();
input.selectAll();
}
}
});
You could check if text is a number with a regex like that:
text.matches("[1-9][0-9]*");
I hope it helps.

How to perform an action when only first key pressed?

I want a JTextFeild event when keyboard button pressed.I want concatenate "ADZ" text to the front whole text.(If we enter "2" whole text should be "ADZ2") THe Action will performed only first key press.After any key pressing action won't be performed.Action will performed only once.
I tried below code,but if type 22 it gives"ADZADZ22".
private void JTextFeild1KeyTyped(java.awt.event.KeyEvent evt) {
String num1 = JTextFeild1.getText();
JTextFeild1.setText("ADZ"+num1);
I want this if type 22, it will gives ADZ22.
A simple way to solve it, is to check if the prefix is already there.
This avoids that the same prefix is added twice.
private void JTextFeild1KeyTyped(java.awt.event.KeyEvent evt) {
String num1 = JTextFeild1.getText();
if (!num1.startsWith("ADZ"))
{
num1 = "ADZ" + num1;
JTextFeild1.setText(num1);
}
...
}
Please note: Java coding rules would suggest to make field names (e.g. jTextField) start with a lower case character. The same goes for method names (e.g. private void jTextField1KeyTyped)
public static int counter = 0;
Maintain a static counter at class level. At key press increase it by one. check :
if(counter == 1) {
// do your operation
}
Check if your JTextField is empty and then set a prefix. This method sets "ADZ" when the field is empty and you type something and then appends everything you type.
public void keyTyped(KeyEvent ke) {
if(txfInput.getText().equals("")) {
txfInput.setText("ADZ");
}
}

Search function for a phonebook.java project

So I've been working on this project PhoneBook.java program for awhile. The program opens up a .txt file and imports it into a List sorted by Lastname, Firstname. I am attempting to write a search function that opens a window, asks you to input a name, then upon clicking ok it should select the searched index. I can not understand why my following code for the searchMI is not working. I appreciate any help you can give me.
public class PhoneBook extends Frame implements ActionListener, ItemListener {
MenuItem newMI, openMI, saveMI, saveAsMI, exitMI;
MenuItem searchMI, deleteMI, updateMI, newEntryMI, sortMI;
String fileName;
List nameList;
List numberList;
TextField lastName, firstName, phoneNumber;
// implementing ActionListener
public void actionPerformed(ActionEvent event) {
Object source = event.getSource();
if(source == newMI)
{
nameList.removeAll();
numberList.removeAll();
fileName = null;
display(-1);
setTitle("White Pages")
}
else if(source == searchMI)
{
String searchName = JOptionPane.showInputDialog(this,
"Please enter a name (last first) to search:");
System.out.println("Name to search: " + searchName);
int index = nameList.getSelectedIndex();
String name = lastName.getText().trim() + " " + firstName.getText().trim();
for(int i=0; i!=index; i++){
if(nameList.equals(searchName)){
nameList.select(index);
}
else
{
System.out.println("Error searching for the name: " + searchName);
}
...
Suggestions
Why this: int index = nameList.getSelectedIndex();? It does not look as if the selected index will give you any useful information here.
This will never work: if(nameList.equals(searchName)){. A List cannot equal a String.
Instead use your for loop, loop through whatever collection holds the Strings, I'm guessing it's the nameList and compare the String held at each item with the entered String.
The for loop should go from i = 0 to i < nameList.getItemCount() (or nameList.size() if it is a java.util.List).
Don't have that else block, else{ System.out.println("Error searching for the name: "... inside of the for loop. Doing that will print out the else Statement many times.
You're better off using the Swing library components not AWT.
You'll want to format your posted code better. Each statement should have its own line. Careful and regular indentations matter.
Since you are using components in your GUI, you may not need that JOptionPane. Could you instead get the search String from one of your text fields?

Display message dialog if JTextField does not contain data

I am writing a BMI calculator application. Currently an error happens which causes the program to stop working if I do not enter data into one field. For instance, there are two JTextFIelds for 'height', one being feet and the other inches. If I just input '6' into the feet JTextField and enter nothing into inches JTextField, then enter my weight in the weight JTextField and click on calculate, it does not work.
What I want to do is display a message dialog saying "Please make sure all fields are filled in" if one field does not contain data.
Below is the ActionHandler code that is added to my 'Calculate' button.
public void actionPerformed(ActionEvent e) {
double heightFT = ((Double.parseDouble(heightFt_TF.getText()));
double heightIn = (Double.parseDouble(heightIn_TF.getText()));
double weight = (Double.parseDouble(weight_TF.getText()));
double totalHeight = (heightFT*12) + heightIn;
BMI = (weight / (totalHeight*totalHeight)) * 703;
String s = BMI+"";
s = s.substring(0,4);
BMI_TF.setText(s);
}
Solved
I have now fixed the problem. What I did was add 'throws NumberFormatException' in the method and did a try catch. In the try code block I wrote the code I want to execute if all data fields are entered. In the catch clause I wrote code that uses the NumberFormatException and simply displays the message dialog with the error message. Now, if one field is not entered, the message dialog appears!
Just check if your JTextField objects contain text.
E.g:
if (heightFt_TF.getText() == null || heightIn_TF.getText() == null || weight_TF.getText() == null) {
JOptionPane.showMessageDialog(null, "Please make sure all fields are filled in");
}
Of course you also have to make sure, that the content of the textfields really contains a number.
Download Apache Commons Lang library and use StringUtils.isBlank(myTextField.getText()); to validate your fields.
public boolean validateFields() {
if (StringUtils.isBlank(heightFt_TF.getText()) {
// show message
return false;
}
if (StringUtils.isBlank(weight_TF.getText()) {
// show message
return false;
}
return true;
}
Only run your calculation if validateFields() returns true.
public boolean validate(JTextField field) {
boolean result = field.getText() != null;
if (result) {
try {
Double.parseDouble(field.getText()));
} catch(NumberFormatException e) {
result = false
}
}
return result;
}

Categories

Resources