java Validations to check if more than one textbox has values - java

I have three text boxes in my html ,where user can input values. In my java class i am doing validations to check if more than one input box has been entered .If user has entered values in two/three textboxes i need to throw an error message. If he hasnt entered the value in three textboxes also i am planning to throw error messsagae. My code is something like this .
if(!dId.equals("") && !PId.equals("") && !PPup.equals("")){
result.addError(new ErrorBO("only one should only be entered"));
}
if(dId.equals("") && PId.equals("") && PPup.equals("")){
result.addError(new ErrorBO(" one should be entered"));
}
dId,PId,PPup are the variables where i have my values. This code fails for the case where the user enters the value in two text boxes. Is there a simplified way to check all the cases.

int numEntered = 0
if(!dId.equals("")) numEntered ++;
if(!pId.equals("")) numEntered ++;
if(!pPup.equals("")) numEntered ++;
if(numEntered != 1) result.addError(new ErrorBO("Enter values in one text box"));
Basically, increase a counter every time a text box has entry. If anything but 1 of them has text, return your error.

Related

How to use JMenuItems to display integers on seperate lines in a JTextArea?

I'm using a JMenu (named Count) with four JMenuItems (named Inc, Dec, Reset, Quit). When I click on any of the menuitems I want it to display the integer in the JTextArea. For example, everytime I click on Inc it should show the integers vertically listed starting from 0. The issue right now is that when I press the Dec menuitem its not taking the last number listed.
I tried to use the getText method but I keep getting a NumberFormatException and saying that the input string is a bunch of numbers e.g.:
0
1
2
3
4
From what I can tell, I am aware that I need to be able to keep track of the last number in a way that all menuitems (aside from the quit menuitem) can access it and change it. I just have no idea how to do it.
Here is one of the ways that I've tried where it gives me the error I mentioned above.
//newLine = "\n";
public void actionPerformed(ActionEvent ae) {
String ac = ae.getActionCommand();
if(ac.equals("Inc")) {
jta.append(count + newLine);
count++;
}
else if(ac.equals("Dec")) {
count = Integer.parseInt(jta.getText());
countText = Integer.toString(count);
jta.append(countText + newLine);
count--;
}
else if(ac.equals("Reset")) {
jta.selectAll();
jta.replaceSelection("0");
count = 0;
}
else if(ac.equals("Quit")) {
System.exit(0);
}
}
I was expecting
0
1
2
3
4
3
2
1
to be displayed in the TextArea when I click on Inc and Dec
But instead its just
0
1
2
3
4
and then I get a NumberFormatException saying that the input string is:
0
1
2
3
4
If possible, I would like the input string to be just the last integer in the textarea.
I hope this makes sense. This is my first time making a post on stackoverflow.
When you get the text, it has returned "0 1 2 3 4" which cannot be parsed an integer, therefore the exception.
If you want to get the last integer in the text field, you need to retrieve the text and find the substring that represents the last integer. Look at the javadocs for String, especially the lastIndexOf(), split(), and substring() methods.
If you have placed each integer on a separate line, and have kept track of the last number entered in an instance variable "count", then you just need to call jta.append( (count-1) + newLine); without having to retrieve the text at all.
Note that your code does not save the last number entered - it saves (last+1)

System.exit(0) reached before maximum user attempts made reached

I may have confused my self with the logic for some time now and I could use some assistance. So I have created this function to return a Voucher # (size is 4-digits). The pre-condition is two characters entered must be correct and in their respective placing below the application reveals the rest of the Voucher digits (when compared with voucher in record).
I am giving the user 3 attempts to search the voucher with the only two known voucher digits. After three attempts and if the voucher does not exist. I'll lock the user and close the app with System.exit(0).
However, System.exit(0) executes when attempt = 3. It seems I don't have control over my loop.
int attempts = 3;
while (attempts != 0){
if(VoucherNumber.charAt(0) == VoucherRecord.charAt(0) &&
VoucherNumber.charAt(1) == VoucherRecord.charAt(1))
System.out.println("Reveal all digits");
}
else if(VoucherNumber.charAt(0) == VoucherRecord.charAt(0) &&
VoucherNumber.charAt(2) == VoucherRecord.charAt(2) ){
System.out.println("Reveal all digits");
}
else{
System.out.println("Reveal all digits");
attempts--;
if (attempts == 0){
System.exit(0);
}
}
You should get new input from user inside the while loop. As it is, you seem to get the input once, then run the loop 3 times with the same input..

Validating user input in java?

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"

How to add ActionEvent to Two JTextFields

Question is: How do i add code to ensure that a table number (tableNumberJTextField) and waiter name (waiterNameJTextField) have been entered? If one or all fields are empty Use a JOptionPane to inform user that both fields must contain Information
At the moment i have:
private void calculateBillJButtonActionPerformed(
ActionEvent event )
{
if(event.getSource() == tableNumberJTextField)
{
}
else
{
JOptionPane.showInputDialog("Information missing");
}
} // end method calculateBillJButtonActionPerformed
Would i need another IF...Else and a JOptionPane in there for WaiterName as well as tableNumberJTextField seen in the code above OR am i completely doing this wrong????
FULL QUESTION THAT I HAVE TO DO IS:
calculateBillJButtonActionPerformed method (which immediately follows dessertJComboBoxItemStateChanged) and add code to ensure that a table number (tableNumberJTextField) and waiter name (waiterNameJTextField) have been entered. If one of these fields is empty, display a JOptionPane informing the user that both fields must contain information. Otherwise, call the calculateSubtotal method, which you implement in the next step, to calculate the subtotal of the bill. The calculateSubtotal method takes no arguments and returns a double containing the subtotal, which you should display in subtotalJTextField. Calculate and display the tax and the total of the bill in JTextFields taxJTextField and totalJTextField, respectively. The tax rate is specified in a constant TAX_RATE.
Presumably, the actionPerformed you're showing is for a button. If so, just check for text in the fields:
String tableNumber = tableNumberJTextField.getText().trim();
String waiterName = waiterNameJTextField.getText().trim();
if (tableNumber.length() == 0 || waiterName.length() == 0)
{
// show an error
}
else
{
// do a calculation
}

Edit Text and CheckBox checking

I currently have 2 checkboxes with an edit text field beside them. There are 4 checkboxes total and I have the logic to check each one and uncheck others if they are checked (almost radio button style). These 2 however could both be checked if they have values in the edit text fields.
However, if the EditText field (which is set to numeric) has a value of 0 or is blank I want it to uncheck the check box and set the value to 0.
Here is the code I have to do this
if (etBase.getText().toString() == "0" || etBase.getText().toString() == ""){
etBase.setText("0");
cbBase.setChecked(false);
} else {
cbBase.setChecked(true);
}
if (etField.getText().toString() == "" || etField.getText().toString() == "0"){
etField.setText("0");
cbField.setChecked(false);
} else {
cbField.setChecked(true);
}
As it sits right now I default the two fields to be "0" when it starts. When this logic runs, it is setting both checkboxes to checked.
I must be missing something here.
To compare string, you must use .equals() function. ( Or .compareTo() but that's no the today's deal)
Ex :
if (etBase.getText().equals("0") || etBase.getText().equals("")){
...
}
var1 == var2 is used to get if these both variable have the same object

Categories

Resources