Check for empty JFormattedTextField - java

I'm new here, and I'd like some help on a small Java project I'm doing. This is the code snippet I need help with:
private void CalculateButtonActionPerformed(java.awt.event.ActionEvent evt)
{
// TODO add your handling code here:
float Principal, Rate, Time, Result, Temp;
Principal = Float.valueOf(PrincipalTextField.getText());
Rate = Float.valueOf(RateTextField.getText());
Time = Float.valueOf(TimeTextField.getText());
Temp = (float) Math.pow((1 + Rate / 100), Time);
Result = Principal * Temp;
ResultTextField.setText(String.valueOf(Result));
}
I'd like to check if PrincipalTextField, OR RateTextField, OR TimeTextField aren't filled by the user, and if so, display a dialog box that asks him/her to recheck them. The text fields are JFormattedTextField variables. I realise that I can do this with a if/else or a while loop, but I'm not sure how to set about doing so. Please help!

You can do something like this:
The getText() returns you a String value. So you can always invoke length() and check whether the length comes to 0 or not. (*I would suggest calling trim() on the String before calling length() to remove any whitespaces)
Next if any of the length comes to be zero, what you want to do is display a Dialog Box. This you can do by calling JOptionPane.showMessageDialog(). You can read more about "How to Make Dialogs" over here.
So, you would do something like this:
String principalText = PrincipalTextField.getText();
String rateText = RateTextField.getText();
String timeText = TimeTextField.getText();
if(principalText.trim().length == 0 || rateText.trim().length == 0 || timeText.trim().length == 0){
JOptionPane.showMessageDialog(null, "YOUR_ERROR_MSG", "ERROR_TITLE", JOptionPane.ERROR_MESSAGE);
}
This might be off-topic, but I would suggest looking at Java Naming Convention. The convention for variables is to compose variable names using mixed case letters starting with a lower case letter

you miss reason for why there is JFormattedTextField
have to set Number Formatter for JFormattedTextField, then
you not need to parsing Float value (better could be to use double)
empty coudl be 0 (zero) value by default
take value in the form ((Number)PrincipalTextField.getValue()).floatValue();
look at code example for tutorial,

Also consider subclassing InputVerifier, as discussed in Validating Input. There's a related example here.

Related

Method to check if label is empty is not working

I am working on a program which uses jLabels and I need to check if label is empty or not. If it's empty it should just pop up a note that it's empty and nothing else, but it actually throws a lot of errors. I'm using label.getText().isEmpty().
Here's the code:
if(Integer.parseInt(najboljsi1.getText())<1||Integer.parseInt(najboljsi1.getText())>17||najboljsi1.getText().isEmpty()||
Integer.parseInt(najboljsi2.getText())<1||Integer.parseInt(najboljsi2.getText())>17||najboljsi2.getText().isEmpty()||
Integer.parseInt(najboljsi3.getText())<1||Integer.parseInt(najboljsi3.getText())>17||najboljsi3.getText().isEmpty()||
Integer.parseInt(najslabsi1.getText())<1||Integer.parseInt(najslabsi1.getText())>17||najslabsi1.getText().isEmpty()||
Integer.parseInt(najslabsi2.getText())<1||Integer.parseInt(najboljsi2.getText())>17||najslabsi2.getText().isEmpty()||
Integer.parseInt(najslabsi3.getText())<1||Integer.parseInt(najslabsi3.getText())>17||najslabsi3.getText().isEmpty())
{
jLabel101.setForeground(Color.red);
jLabel101.setText("Eno ali več vnesenih števil ni v pravilnem obsegu (1-16)!");
}
else
{
jLabel101.setText("");
int a=Integer.parseInt(najboljsi1.getText());
tabela[a-1]+=3;
int b=Integer.parseInt(najboljsi2.getText());
tabela[b-1]+=2;
int c=Integer.parseInt(najboljsi3.getText());
tabela[c-1]+=1;
int d=Integer.parseInt(najslabsi1.getText());
tabela[d-1]-=3;
int e=Integer.parseInt(najslabsi2.getText());
tabela[e-1]-=2;
int f=Integer.parseInt(najslabsi3.getText());
tabela[f-1]-=1;
najboljsi1.setText("");
najboljsi2.setText("");
najboljsi3.setText("");
najslabsi1.setText("");
najslabsi2.setText("");
najslabsi3.setText("");
count++;
jLabel1.setText("Učenec "+count);
}
Everything else in if statement works ok, if value is lower than 1 or higher than 16, it throws a pop up.
Yes, you must test najboljsi1.getText().isEmpty() BEFORE any parsing of najboljsi1.getText().
Your if would become:
if(najboljsi1.getText().isEmpty()||Integer.parseInt(najboljsi1.getText())<1||Integer.parseInt(najboljsi1.getText())>17||
najboljsi2.getText().isEmpty()||Integer.parseInt(najboljsi2.getText())<1||Integer.parseInt(najboljsi2.getText())>17||
etc...
If you do Integer.parseInt(najboljsi2.getText()) on a label with the textn "" (empty String), it won't be an integer. An exception will be thrown.
I think your problem is in the use of the "Integer.parseInt" without any check! If, for example, the variable contains an empty string, it will throw an Exception and your if clause will never work!
I would manage the situation with a double check.
Check if it is already a number (this guide could help
check-if-variable-is-a-number-in-javascript)
Then, if it is a string, check if it is empty and if it actually contains a string (the following post could also help check-whether-an-input-string-contains-a-number-in-javascript)
Ps. Sorry, I modified the answer with some extra links

concatenation of variables with probability of null or 0

Ok i don't know how to exactly explain completely what my issue is i'm facing to get what i want, but the basis of what i'm trying to accomplish here is...i don't want a -> ; <- to show up if the variable is Null or 0. Something I've attempted so far is a scanner input where when you run the code it asks to input values that are > 0 and if you input one thats not it'll give an invalid input error. Im trying to find a different method where its not needed to keep repeating this method for 20 or more. Like i said im just trying to have it input the numbers automatically, and if theres no number in one of the variables it would skip it and not put another " ; " and just put the ones that do have numbers with the semicolon. So what i'm looking at to accomplish is listed in the image bellow :
I had difficulties to understand your question. I am also not an english speaking person....
If I understood you want this:
String a,b,c,d,e, all;
all = "";
if(a!=null && a!=0){
all += a;
}
if(b!=null && b!=0){
all += b;
}
if(c!=null && c!=0){
all += c;
}
...
if(all != ""){
//something
} else {
// something else
}
Note that I am not permutating, I am sequencially checking for values in each variable then performing the desired effect.... I just concatenated strings, if you want to add stuffs like (space),; (semicolon), its up to you.

Passing a variable to method and stopping the variable from resetting

I understand how to pass a variable to another method and I even learned how to do multiple variables to a single method. My problem is I am trying to make a switch statement, when the user inputs a symptom for digoxin(medication for heart) in the statement I want to award him 10 points store it in a variable, and when the user enters another symptom I want to store that in variable as well in a new method. My problem is that after I send the variable to my method and continue with the program it inevitably resets it to zero, and thus dooming my efforts.
Code:
switch(input5) {
case "Vomiting":
score = 0;
num = 0;
score = num + 10;
getMethod(score,0);
System.out.println(getMethod(num));
JOptionPane.showMessageDialog (null,"you're correct") ;
break;
case "Dizziness":
JOptionPane.showMessageDialog (null,"you're correct") ;
score = num + 10;
getMethod(0,score);
break;
case "Confusion":
JOptionPane.showMessageDialog (null,"you're correct");
break;
case "Vision":
JOptionPane.showMessageDialog (null,"you're correct");
break;
default :
JOptionPane.showMessageDialog (null,"you're Wrong");
break;
}
...
static int getMethod(int total) {
int amount = total;
int amount2 = total2;
int result = amount + amount2;
return result;
}
The problem with this question is that it is so poorly phrased that it is difficult to understand what you actually think is happening. Unless we understand that, it is hard to answer it properly. So I'm just going to point out some things that appear to be errors in your thinking.
Variables don't "reset" in Java. In this case that the problem is that your getMethod method doesn't update score.
If a method returns a value, and that value isn't assigned to something then it is thrown away. In your case you are not assigning the value returned by getMethod in the places that you are calling it.
In Java, arguments are passed to methods "by value". The upshot is that something like this won't work:
int test = 1;
increment(test, 2);
public void increment(int value, int by) {
// FAIL - the local copy of "value" is incremented, but the
// the original "test" variable is not touched.
value = value + by;
}
Note that this has nothing to do with the names of the variable. The issue is that the variable inside the method is not "connected" in any way to the variable used at the call site. The method updates the former ... and not the latter.
A couple things that need to be said about your code:
It is important to indent your code consistently. There are style guides that tell you what to do. (We've reindented your code in a way that would be acceptable under most style guidelines.)
It is important to use sensible and informative names for things like methods, variables and classes. This helps readers understand what the code author intended the code to do / mean. In your case "getMethod" tells the reader nothing about what the method is supposed to do.
Methods should also have javadoc comments that state what they are supposed to do, what the arguments and results mean, and so on.
i think the issue here is that every time you enter something and enter your switch statement, it resets the score to 0.
switch(input5){
case "Vomiting":
score = 0;
I think you need to set score to 0 before the first input, and not reset it every time you put in vomiting. I can't exactly follow your code, please link the full class.
Try this:
score = getMethod(score, 0);
In java, primitives are "passed by value". The value, not the variable, is passed to the method. Changing the value within the method does nothing to the variable that was used to call the method.
Create a static global variable to maintain or persist the score. This will allow you to make subsequent calls to your method and still keep track of an accurate score.
So, create a global variable public static int score = 0;. Inside of your method you can get rid of the score variable initialization to zero score = 0; since you will use the global score variable.

if statement with integers [duplicate]

This question already has answers here:
Why does my if condition not accept an integer in java?
(7 answers)
Closed 3 years ago.
I'm new at Java. I'm looking for some help with homework. I wont post the full code I was doing that originally but I dont think it will help me learn it.
I have a program working with classes. I have a class that will validate a selection and a class that has my setters and getters and a class that the professor coded with the IO for the program (it's an addres book)
I have a statement in my main like this that says
//create new scanner
Scanner ip = new Scanner(System.in);
System.out.println();
int menuNumber = Validator.getInt(ip, "Enter menu number: ", 1, 3);
if (menuNumber = 1)
{
//print address book
}
else if (menuNumber = 2)
{
// get input from user
}
else
{
Exit
}
If you look at my if statement if (menuNumber = 1) I get a red line that tells me I cannot convert an int to boolean. I thought the answer was if (menuNumber.equals(1)) but that also gave me a similar error.
I'm not 100% on what I can do to fix it so I wanted to ask for help. Do I need to convert my entry to a string? Right now my validator looks something like:
if (int < 1)
print "Error entry must be 1, 2 or 3)
else if (int > 3)
print "error entry must 1, 2, or 3)
else
print "invalid entry"
If I convert my main to a string instead of an int wont I have to change this all up as well?
Thanks again for helping me I haven't been diong that great and I want to get a good chunk of the assignment knocked out.
if (menuNumber = 1)
should be
if (menuNumber == 1)
The former assigns the value 1 to menuNumber, the latter tests if menuNumber is equal to 1.
The reason you get cannot convert an int to boolean is that Java expects a boolean in the if(...) construct - but menuNumber is an int. The expression menuNumber == 1 returns a boolean, which is what is needed.
It's a common mix-up in various languages. I think you can set the Java compiler to warn you of other likely cases of this error.
A trick used in some languages is to do the comparison the other way round: (1 == menuNumber) so that if you accidentally type = you will get a compiler error rather than a silent bug.
This is known as a Yoda Condition.
In Java, a similar trick can be used if you are comparing objects using the .equals() method (not ==), and one of them could be null:
if(myString.equals("abc"))
may produce a NullPointerException if myString is null. But:
if("abc".equals(myString))
will cope, and will just return false if myString is null.
I get a red line that tells me I cannot convert an int to boolean.
Thats because = is an assignment operator. What you need to use is == operator.
A single equal sign is assignment: you assign value to a variable this way. use two equal signs (==) for comparison:
if ($menuNumber = 1) {
Update: forgot dollar sign: $menuNumber

Simple Java Validation

I am a web app programmer (mostly PHP/JavaScript/Ajax etc).
There is this payroll appplication that I want to code in java. I needed to know where I could find tutorials on how to do basic validation in java e.g. checking if a textfield is null, making sure only integers are allowed etc.
I have this basic program that runs and created a jFrame form:
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
double num1, num2, result;
num1 = Double.parseDouble(jTextField1.getText());
num2 = Double.parseDouble(jTextField2.getText());
result = num1 + num2;
jLabel4.setText(String.valueOf(result));
}
How can I for instance get to validate that jTextField's 1 and 2 are not left blank. i.e., to return an error box that lets a user know that both fields cannot be left blank?
I was trying this as a tester:
if(num1 == 0 && num2 == 0)
{
JOptionPane.showMessageDialog(null, "You must fill in all fields");
}
But this doesnt work at all
If it belongs to swing then check
jTextField1.getText().trim().length > 0 && jTextField2.getText().trim().length > 0
or
!jTextField1.getText().equals("") && !jTextField2.getText().equals("")
Also read some tutorial on swing components.
For a beginner like yourself, using a standard library like Apache Commons / Lang will probably be the easiest:
check if a value is numeric:
// removes whitespace, converts to null if only whitespace,
// checks whether the remeining string is numeric only
StringUtils.isNumeric(StringUtils.stripToNull(jTextField1.getText()));
Get the numeric value:
int value = Integer.parseInt(jTextField.getText().trim());
Have a look at the recent JSR-303 standard: http://jcp.org/en/jsr/detail?id=303. It also integrates well with Spring.
In order to test Java application you can use JUNIT http://junit.sourceforge.net/ for whitebox testing

Categories

Resources