Multiple textfields with one joptionpane [duplicate] - java

This question already has answers here:
JOptionPane - check user input and prevent from closing until conditions are met
(2 answers)
Closed 6 years ago.
I want a user to input 4 things (first name, last name, email and phone number) and in case he misses one or more just one JOptionPane window would show.
String firstname = TF_1.getText();
String lastname = TF_2.getText();
String email = TF_3.getText();
String phonenumber = TF_4.getText();
if (TF_1.equals("") ||
TF_2.equals("") ||
TF_3.equals("") ||
TF_4.equals("")) {
JOptionPane.showMessageDialog(null, "All text fields must be filled");

First thing personally I don't like one generic message for all fields it puts users in confusion what they have not filled. You can use a flow that you check all field one by one and if a field is empty show error for it and return from their.
Secondly check on string fields firstname, lastname etc not on TF_1.
public boolean isEmpty(String... fields)
{
for (String string : fields)
{
if (null == string || string.trim().length() == 0)
{
// return true of filed is blank
return true;
}
}
return false;
}
You can use this method and pass all your fields to check if any of them is empty.

Related

Conditional using a string in Java after using Scanner [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 4 years ago.
It always give the second conditional regardless of the input. Is (userName == "Charles") the correct way of doing this conditional? or do i need something else.
import java.util.Scanner;
public class Name_input {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String userName = input.next();
System.out.println(userName);
if (userName == "Charles")
{
System.out.println("Correct Name");
}
else if (userName != "Charles")
{
System.out.println("Incorrect Name");
}
}
}
Is (userName == "Charles") the correct way of doing this conditional
No You don't use "==" to compare strings.
Instead you should be using the equals(...) method:
if ( "Charles".equals( userName ) )
Note I reversed the order of the comparison. This will prevent a NPE if the username is ever null.
System.out.println(userName);
Does that display the expected value? Do you need to use the trim() method?
else if (userName != "Charles")
Also, there is no need for the "else if". The name is either "Charles" or it isn't so you don't need the additional "if" statement.

How to perform a boolean check in Processing on a value from serial string? [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 5 years ago.
I have a simple push button connected to pin 2 on my Arduino. I can read this value and print it to the serial monitor without any trouble:
int pushButton = 2;
void setup() {
Serial.begin(9600);
pinMode(pushButton, INPUT);
}
void loop() {
int buttonState = digitalRead(pushButton);
Serial.println(buttonState);
delay(1); // delay in between reads for stability
}
This prints a value of 0 when the button is not pressed, and 1 if it is.
In Processing, I want to check if the value is zero or one, and perform some conditional logic. But I can't get the equality right:
Serial myPort;
String resultString;
void setup(){
size(640,480);
printArray(Serial.list());
String portName = Serial.list()[2];
myPort = new Serial(this,portName,9600);
myPort.bufferUntil(10);
}
void draw() {
//
}
void serialEvent(Serial myPort){
String inputString = myPort.readStringUntil(10); //until newline or ("\n");
inputString = trim(inputString);
println(inputString);
if (inputString == "1"){ //this doesn't work, even though println will render ("1") plus the newline if button is pushed.
println("on");
} else {
println("off");
}
}
How do I set up this conditional to do one thing if the button is pushed, and another if it is not?
I've tried converting the string to an int using
inputInt = Integer.parseInt(inputString);
and then performing the check, but it didn't work.
You are using Java on host, are you?
if (inputString == "1")
Sure this fails, as these are different objects... Try this instead:
if (inputString.equals("1"))

Method won't return an updated String

I have a method that is supposed to get the input of a String from a user and validate 4 things:
that its only 1 word, doesn't contain spaces, doesn't contain numbers, and isn't blank/had the enter key pressed.
If any of these issues occur then an error msg is printed and the method is called again to re-prompt the user for input. If the string meets the requirements than the method returns the String.
In most cases the method works as intended, however, if I enter an incorrect repsonse the first time around then even after it prompts me with the error and I enter the correct response it returns the incorrect response I entered the first time. Can someone please explain why this is happening?
public static String getName() {
//Prompt User for Name and Store it as the tmp String
System.out.print("Please enter the target string here: ");
String tmp = in.nextLine();
//Check to see if the string is blank, contains more than one word, or contains numbers. If so, give error and re-prompt
if(tmp.equals("") || tmp.contains(" ") || tmp.contains("1") || tmp.contains("2") || tmp.contains("3") || tmp.contains("4")
|| tmp.contains("5") || tmp.contains("6") || tmp.contains("7") || tmp.contains("8") || tmp.contains("9") || tmp.contains("0")) {
System.out.println("\nYou entered an invalid response, please try again\n");
getName();
}
//Return the String
return tmp;
}
You must assign the string:
tmp = getName();

Java executuion of else is expected but always if is executing [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 5 years ago.
I think you have understood what I am trying to do. Give a prompt when user press OK without changing he default TEXT. But the first condition seems to be TRUE. I don't know if it is a problem of if statement or my code.I have included the whole class .Be sure to read comment to avoid reading unnessasary code.
ok = JButton
text = JTextField
int c = 0;
public class handler implements ActionListener{
public void actionPerformed(ActionEvent e){
//
//The following lines are not nessary for the question.
if(ok==e.getSource()){
if(!(male.isSelected() || female.isSelected()) && c==0){
c++;
JOptionPane.showMessageDialog(null,"Hey you haven't selected your gender. Do you wish to proceed","Warning",JOptionPane.PLAIN_MESSAGE);
}
}
//well these lines were not necessary
//They were just in the same class
//
//
//Here the else condition should execute
//
if(ok==e.getSource()) && (text.getText() != "Enter your name")){
JOptionPane.showMessageDialog(null,"Your name is "+text.getText(),"Name",JOptionPane.PLAIN_MESSAGE);
}else if((ok==e.getSource()) && (text.getText() == "Enter your name")){
JOptionPane.showMessageDialog(null,"Hey type in your name buddy ","Name",JOptionPane.PLAIN_MESSAGE);
}
}
}
So the problem is that the if condition gets executed, while the else if should when we are not changing the default text "Enter your name". I tried changing the text and in that condition also the if block is executing. And please do a full explanation of your answer. I am a beginner with rusted skills.
You need use other method to compare the strings, for example here:
text.getText() == "Enter your name")
you can use equals:
text.getText().equals("Enter your name")
You should do it in the two places into your original code.

How to compare 2 passwords in java? [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 6 years ago.
I'm working on a project with a registration form. The form asks the user to
enter a password of their choice in a JPassword Field, and to enter it again in another JPassword Field.
I'm using a JOptionPane to prompt the user if the passwords do not match. but when i use passwordField.getPassword().toString() on the two, they don't match.
I have tried entering a basic "12345" for example on both but i still have no luck.
i know you should use .equals(), but what is the equivalent to this for "not equals" without using the "!=" operator.
here is the following code.
if(e.getSource() == submit)
{
String name = nameTextField.getText();
String address = addressTextField.getText();
String phoneNumber = numberTextField.getText();
String dob = datePicker.getDateFormatString();
String password = passwordField.getPassword().toString();
String password2 = passwordFieldTwo.getPassword().toString();
try
{
//If the user leaves the field empty
if(name == null || address == null || phoneNumber == null || dob == null
|| password == null || password2 == null)
{
//Error message appears to prompt the user to
//complete the form
JOptionPane.showMessageDialog(null, "All fields must be complete to submit.", "Woops", JOptionPane.ERROR_MESSAGE);
}
if(password != password2)
{
JOptionPane.showMessageDialog(null, "Passwords do not match.", "Woops", JOptionPane.ERROR_MESSAGE);
passwordField.setText(null);
passwordFieldTwo.setText(null);
}
Any help with this would be much appreciated.
The != related to equals() for String comparison is expressed by !x.equals(y)
As an example lets take your code, to see if the two passwords not match do the following:
if (!Arrays.equals(passwordField.getPassword(), passwordFieldTwo.getPassword())) {
JOptionPane.showMessageDialog(null, "Passwords do not match.", "Woops", JOptionPane.ERROR_MESSAGE);
}

Categories