Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 years ago.
Improve this question
My code executes properly only when it is not placed within the if statement. Why is that happening? I think there has to be something wrong with the condition which is supposed to check if Strings which are coming from JTextFields aren't empty.
Here is my code which is working without using the if statement:
user1.name = name1;
user1.password = pass1;
user1.ip = i1;
save(user1);
And here is the badly implemented if statement:
if(!name1.equals("") && !pass1.equals("") && !i1.equals("")) {
user1.name = name1;
user1.password = pass1;
user1.ip = i1;
save(user1);
}
Note: name1, pass1 and i1 are all Strings of pretty basic values. name1 can be Bob, pass1 can be Bob123 and i1 can be 192.168.32.1
Since you are trying to
check if Strings which are coming from JTextFields aren't empty
check the doc for the isEmpty() method and use something like:
if((name1 != null && !name1.isEmpty()) &&
(pass1 != null && !pass1.isEmpty()) &&
(i1 != null && !i1.isEmpty()) ) {
//....
}
A distinct non-answer: you are doing the validation in the wrong place!
Your UI elements should only allow you to trigger that save action when the required values are present. Create a user experience that prevents the user from making mistakes. Instead of investing times to discover "oh, the user made a mistake"!
In other words: you should listen to status changes on your text fields, and only when all three textfields have an non empty content, only then, you enable your Save button/menu item! And when one of field turns empty again, you better disable that button/menu item.
Related
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 days ago.
Improve this question
I am in my first semester of a Java Course. I am struggling to understand how I put exclusiveness on a statement. I am writing a Class for an Object Couch. I have tried to build a well formed class, but for the outcome from my main, in the console it must only have 4 or 8 legs on the couch. There is no user input as I am hard coding the variables, but I want to be sure that if I hard code for 5 legs it will stop me or an error message will pop up. Any suggestions?
public void setNbrLegs(int nbrLegs){
if ((nbrLegs == 2) || (nbrLegs == 4)){
this.nbrLegs = nbrLegs;
}
}
I tried putting an "else" with a message that that number is bad, but what is did was bypass my error message and just insert the incorrect number ofLegs as 5.
Consider looking for the opposite: a condition where you must fail. From there, you can use runtime exceptions to ensure a few things:
The invalid state is not applied
A developer passing this invalid state will get an exception, and have a clear reason to fix their code
You no longer have to worry about invalid state further on in the method (i.e. legs will only be 2 or 4 further on).
In doing so, your method may end up looking like this:
public void setNbrLegs(int legs) {
if (legs != 4 && legs != 2) {
throw new IllegalArgumentException("Can only have 2 or 4 legs");
}
this.nbrLegs = legs;
}
This preconditional checking is also good to do early in your methods (fast-fail), as it will prevent excess work being done for a method that will only "fail".
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
Hi friends I've been difficult to get my row in SQL. When I use mouse event in Java just 4 field in my row data appear.
private void jtb_dataasetMouseClicked(java.awt.event.MouseEvent evt) {
// TODO add your handling code here:
// Mouse Pilih
int bar = jtb_dataaset.getSelectedRow();
String a = jtb_dataaset.getValueAt(bar, 0).toString();
jid_aset1.setText(a);
String b = tabmode.getValueAt(bar, 1).toString();
jnm_aset.setText(b);
String c = tabmode.getValueAt(bar, 2).toString();
jmrk.setText(c);
String d = tabmode.getValueAt(bar, 3).toString();
jsernum.setText(d);
String e = tabmode.getValueAt(bar, 5).toString();
jkondisi.setSelectedItem(e);
}
This is look like when I choose the data
I still difficult, please correct me if I made a mistake. I use the enum string in string.
From the javadoc for method setSelectedItem(Object anObject)
If anObject is not in the list and the combo box is uneditable, it will not change the current selection
Looks like the value in your JTable does not match a value in your JComboBox.
I suggest printing out the JTable value.
After this line of the code you posted...
String e = tabmode.getValueAt(bar, 5).toString();
add this line...
System.out.println("^" + e + "^");
Then compare that with the value that you think should be matched in your JComboBox.
A good programmer must know how to debug code. Have you read this Web page?
How to debug small programs
And regarding posting questions, in general, I recommend that you read this Web page.
How do I ask a good question?
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
Here's a brief explanation of my program:
User keys in data
Data is stored in vector
User may choose to key in data again...
Before the program is closed, a summary screen of data will be displayed.
The problem I'm facing now is that the for loop is executed even before data is stored in it, while what I want is for the for loop to run only summary screen is displayed.
Is there a way to tackle this problem?
SummaryPanel.class (Partial code)
list = new JList<String>();
scroll = new JScrollPane(list);
model = new DefaultListModel<String>();
for(int i=0; i<con.retrievePersonalVector().size(); i++){
model.addElement(((PersonalRecord)con.retrievePersonalVector().get(i)).getLoginName()); //NPE
list.setModel(model);
list.addListSelectionListener(new ListSelectionListener() {
public void valueChanged(ListSelectionEvent e) {
int selected = list.getSelectedIndex();
}
});
A couple of things:
Vector<?> persRecs = con.retrievePersonalVector();
for (int i = 0; i < persRecs.size(); i++) {
PersonalRecord persRec = (PersonalRecord)persRecs.get(i);
if (persRec != null) (
model.addElement(persRec.getLoginName());
}
}
In the original code the retrievePersonalVector was done at every loop step twice: checking the size and getting an element. Instead of 2N times, retrieval is now done once.
Then the model was passed to the component in the loop. Mabye a genuine decision, to see a something, but that probably does not work here, hence I close the loop early. Also adding a listener should be done once. (Or you maybe lost a } on copying together the question.
First of all, you should not use Vector anymore. Prefer List<T> list = Collections.synchronizedList(new ArrayList<T>()). Secondly, if the NullPointerException is indeed thrown where you spot it, it is probably because the Vector contains some null elements, so you should insure that you do not store any null element. Last, why not checking if the summary panel is displayed before looping (either with an isVisible() or a local boolean) ?
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I am very new to Java, but I am really enthusiastic to learn it. I would like to solve the problem by myself step by step
I tried to do my homework piece by piece.
I want to ask users to put 9 digit zip code, for example 701152014, not for 5 digit like 70115.
I wanted to keep asking users until they type 9 digits like 701152014
if they put 5 digits I want to keep asking please type 9 digit.
I use NetBean.
System.out.println(zipNew); This part, something wrong with it.it says error.
so I wanted to prompt user until users would type 9 digit zip code.
how can I do that? Thank you so much.
Thank you so much for teaching me. I really would like to learn Java. Thank you.
package week7;
import javax.swing.*;
public class test {
public static void main(String[] args){
//Scanner scanner = new Scanner(System.in);
String zip=JOptionPane.showInputDialog(null,"Enter your zip");
String zipNew;
int ziplength = (zip.length());
if (ziplength == 9){
zipNew = zip;
}
else if (ziplength !=9)
{
String zip = JOptionPane.showInputDialog(null,"please type 9 digit zip code not 5 digit"); //----this part is wrong
}
System.out.println(zipNew); //----this part is wrong,
}
Normally, I'd use a JFormattedField and/or DocumentFilter, but lets keep it simple...
The basic idea is, you need to loop until you get what you need, for example...
String zip = null;
do {
zip = JOptionPane.showInputDialog(null, "Enter your zip");
} while (zip != null && zip.length() < 9);
System.out.println("zip = " + zip);
This will loop until the user presses [Cancel] or the value they enter has 9 characters. You need to beware, this can result in zip been equal to null and you will need to check for this. Also, there is nothing stopping the user from entering non-numeric values...
Take a closer look at The while and do-while Statements for more details
First off, the formatting is terrible. Not sure if it occurred when posting it here and you didn't actually use that formatting, but you might wanna make it more readable.
You declare the String zip twice. You can't have two variables of the same name in the same class, so in your else if condition (you don't need the if ziplength != 9 as the else guarantees that condition is true) change the name of the String or don't declare the variable again (e.g. say zip = blahblah not String zip = blahblah in the else).
To answer your question, use a do-while loop. Here's an example:
String zip;
do {
zip = blahblah
} while (zip.length != 9)
My assumption is that in the line :
int ziplength = (zip.length());
You are simply not getting the length of zipNew, but instead the length of zip, which doesn't appear to have been declared anywhere.
I would suggest changing this line to :
int ziplength = (zipNew.length());
I have very little experience with java, but just from broad understanding of other languages, I believe you've just made a simple mistake.
Hope this works!
Cheers,
Mike
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Closed 9 years ago.
Improve this question
I need to check 9 conditions for true or false and they need to be all true in one time.
How can it be possible checked, besides
if (condition1 && condition2 && condition3 ... && condition9) {
...
}
Think I used word "condition" right.
It is hard to know if you don't show more code than that.....
However, if I only have that piece of code, I can recommend three things:
1. If you have this information, start with the condition that is most likely to be false, that may improve performance..... more information here short circuit
2. Another thing, if you have all the conditions in an array, you can loop trough the array... Something like this:
public boolean testCondition(boolean conditionsArray[]){
for(int i = 0; i < array.length; i++){
if(!conditionsArray[i])
return false;
}
return true;
}
Post more code and I will try to improve my answer.
3. You might want to rethink about the data structures also. Probably something is not very clean in your design if you need to test for 9 given conditions like that (just probably).
Hope it helps.
Whenever I get into such a situation in code, I know I'm doing it wrong, and need to rethink my object structure.
However, just at the pure level of the question, as long as the conditions are in a collection of some kind, this will work:
boolean allTrue = true;
for (boolean condition : conditions) {
allTrue &= condition;
}
And then do the if on the allTrue variable. Note that I am assuming that the collection is not empty, or if it is, that should be regarded as a true condition.
Most likely in the real world you have to wrap these conditions in some kind of object with a common interface with a method that returns the boolean and use that, rather than having a collection of pure booleans.