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
Related
My guessing game takes either 5, 10, or 20 guesses from a user and they are supposed to try to guess a random number chosen by the computer. Everything in my code is working except this: when the code asks the user whether they want 5, 10, or 20 guesses, if the user were to enter 15, for example, which is not one of the options, it goes on and starts asking for their guesses. I need some type of validation that will make sure they enter one of the options. I'm not sure where or how to include this in the correct way since I am new to programming. I've tried several different ways but get errors for all. What I need is if the user puts a number that is not one of the options, it should just ask them again until they input one of the options. Can someone show me how I should do this?
First of all if (answer.length() ==3) makes no sense.
Maybe you meant:
if(answer.equals("yes"))
Besides, to accomplish what you want I would use a Set containing the valid guesses numbers. It is scalable and makes much more sense than checking against multiple values in an if clause. It will look like this:
Set<Integer> validNumberOfGuesses = new HashSet<Integer>(Arrays.asList(5, 10, 20));
int numberOfGuesses = scan.nextInt();
while (!validNumberOfGuesses.contains(numberOfGuesses)) {
/* ask again */
System.out.println(numberOfGuesses + " is not a valid number of guesses, please try again");
numberOfGuesses = scan.nextInt();
}
Take input from the user inside a loop. For example:
System.out.print("How many guesses would you like? (5, 10, 20)");
do {
int numberOfGuesses = scan.nextInt();
//on correct guess, break out of the loop
if(numberOfGuesses == 5 || numberOfGuesses == 10 || numberOfGuesses == 20)
break;
System.out.print("Please enter a guess having one of these values (5, 10, 20)");
} while (true);
Unless the user, enters one of the three values, he/she will kept being prompted to enter a correct guess value.
Java has the continue keyword that jumps to start of the current loop when run. See The Continue Statement documentation.
Once you have your user input you can do something like
if (numberOfGuesses != 5 && numberOfGuesses != 10 && numberOfGuesses != 20) {
continue; // jumps to start of while loop block, without running conditional
}
When you receive the "numberOfGuesses" you should check the value of that number before moving on. Otherwise you just move on in your code because you don't actually validate the number.
It may be a good idea to creat a function that returns a boolean value and then you can check the number there.
boolean isValidOption(int number)
In the function you want to perform some comparison and validate. Since you have three options you can opt for something like
if (number == 5 || ... )
You can consider how you'll verify the value as there are many ways. Just compare with valid numbers you know you want, you can do some if statements, or place the numbers in an array and compare the value while iterating through the array, and so on. Hope that helps you get started and happy coding!
Edit: Lastly I should have mentioned, but you need to consider the flow of your code. A loop of somesort like while(!isValidOption()) for your check should be use. Loop around the instructions until the user enters a valid option. You need to consider order of operations here in your code and understand the computer doesn't think for you. It does what you tell it, so understand what you are trying to tell it here. I want to step into my game, if and only if, the condition of isValidOption is met for example.
What you need to do is to stay in the loop until you get input that satisfy your demands for example you can use the following function
private int getNumberOfGuesses(Scanner scan) {
int numberOfGuesses;
boolean numberOfGuesesIsValid;
do {
System.out.println("How many guesses would you like? (5, 10, 20)");
numberOfGuesses = scan.nextInt();
numberOfGuesesIsValid = numberOfGuesses == 5 || numberOfGuesses == 10 || numberOfGuesses == 20;
if (!numberOfGuesesIsValid) {
System.out.print("Wrong option !!!");
}
} while (!numberOfGuesesIsValid);
return numberOfGuesses;
}
you can write your code inside a loop to make sure the value is either 5,10 or 20
while(numberOfGuesses!=5||numberOfGuesses!=10||numberOfGuesses=!20);
and the condition if(answer.length()==3 can cause errors. it means it will work every time the input is of length 3,even "noo"
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.
i was trying to write some C++ codes into java, now i have writter following code into java but it is throwing errors!
if(ShapeNotFound && xd*yd - nPixel[k] < xd+yd) // Condition for RECTANGLE
{
System.out.print("\n "+in+" \t Rectangle \n");
fileWriter3.write("\n "+in+" \t Rectangle \n");
Shape[k] = 2;
ShapeNotFound = 0;
}
I am getting following error :
The operator && is undefined for the argument type(s) int, boolean
Please help, tell me how to write the above if condition correctly in java
C and C++ both assume that for integers 0 is false and all other values are true.
Java does not make the same assumption so you need to add a check for int!=0 into the expression i.e.:
if((ShapeNotFound!=0) && (xd*yd - nPixel[k] < xd+yd))
Or alternatively your ShapeNotFound variable should be of type boolean not int.
It would be worth converting variable names etc to Java style guidelines as well.
Java can not convert int into boolean automatically.
It looks like ShapeNotFound is an integer, but you're implicitly treating it like a boolean (true or false). Java only likes genuinely boolean expressions, so you'll need to change the condition to something like this:
if (ShapeNotFound != 0 && xd*yd - nPixel[k] < xd+yd)
For readability, I'd suggest putting some brackets round each part of the condition. That's an issue of personal preference though.
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.
I keep getting the following errors:
Cannot find symbol
Variable find
cannot find symbol
method getdata(int)
I am sure I am making this way more difficult than it is, but I am not sure how make this work so that the return from searching through the array, can be seen and evaluated by the if statement.
//assigns manager identification
manID = keyboard.nextInt();
//Fibonacci binary array for passwords
int[] passWArray = {00000000,00000001,00000001,00000010,00000011,00000101,00001000,00001101};
//item = find.getdata(manID);
if (getdata(manID) != -1)
{
//Do work here
dblPayRate = 10.85;
dblGrossPay = (intHours * dblPayRate) + (15.00);
dblTaxes = dblGrossPay * 0.19;
dblGrossPay -= dblTaxes;
//Print information to user
System.out.print("\n\n$" + df2.format(dblTaxes) +
" was withheld from this paycheck in taxes after working "+ intHours + " hours.\n\n");
System.out.print("The amount \"Employer Here\" owes you is $" + df2.format(dblGrossPay) + "\n");
}
else
{
// Dialog box for incorrect password
JOptionPane.showMessageDialog(null, "Invalid Entry! Contact the BOFH!");
//exits program (Note: needed for any JOptionPane programs)
System.exit(0);
}
}// end of long if statement for >50 hours
}//end of main method
public int find(int[] passWArray, int manID)
{
//search for manID in passWArray array
for (int index = 0; index < passWArray.length; index++)
if ( passWArray[index] == manID )
return manID;
//-1 indicates the value was not found
return -1;
}// end of find method
Change
if (getdata(manID) != -1)
into
if (find(passWArray , manID) != -1)
BTW those numbers don't magically become binary because they only contain 0's and 1's. Here's a hint:
int thirteen = Integer.parseInt("00001101", 2)
EDIT: in response to your next error
For now make the method static:
public static int find(int[] passWArray, int manID)
Eventually you might want to think about your 'Object-Oriented design' and just use the main() method as an entry point. Within main you create an instance of a class and let it do its work. In this way you can use the powers of O-O like encapsulation and inheritance and don't have to make everything static.
EDIT2: Afterthought
Your program seems to have the following 'actions':
user interaction
authentication
calculation
And there seem to be the following 'things' in your domain:
user
password
keyboard
display (command line and screen)
calculation
A good rule of thumb for an O-O design is to convert some of the 'things' and 'actions' already present in your domain into classes. A good class has a single responsibility and shares as little as possible of its data and methods with other classes (this is called information hiding).
Here's a class diagram that comes to mind:
User (represents a user, contains a single field 'password')
Authenticator (authenticates a user, contains the list of allowed passwords)
Console (all user interaction, either use System.out/in or Swing, but don't mix them)
Calculator (it calculates shit)