how to handle java null values - java

Im developing a small app and I wants to get the total when I click the button total . But if there are null values the code code dosen't work .So additionally following code was added .
int QtyOfChickenBurger;
if ((textField.getText().equals(null))) {
QtyOfChickenBurger = Integer.parseInt(textField.getText())*0;
} else {
QtyOfChickenBurger = Integer.parseInt(textField.getText()) * 70;
}
But still my application don't output the total when the textField is empty. So please help me to fix this.This is the full code.
JButton bttotal = new JButton("Total");
bttotal.setBounds(21, 37, 145, 25);
bttotal.setFont(new Font("Thoma", Font.PLAIN, 12));
bttotal.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg) {
int QtyOfChickenBurger;
if ((textField.getText().equals(null))) {
QtyOfChickenBurger = Integer.parseInt(textField.getText())*0;
} else {
QtyOfChickenBurger = Integer.parseInt(textField.getText()) * 70;
}
int QtyOfChickenBurgerMeal = Integer.parseInt(textField_2.getText()) * 120;
int QtyOfCheeseBurger = Integer.parseInt(textField_3.getText()) * 340;
int QtyOfDrinks = Integer.parseInt(enterQTY.getText());
int spriteCost = Integer.parseInt(enterQTY.getText()) * 55;
int cokaColaCost = Integer.parseInt(enterQTY.getText()) * 60;
int pepsiCost = Integer.parseInt(enterQTY.getText()) * 40;
int lemonJuceCost = Integer.parseInt(enterQTY.getText()) * 35;
int sum = (QtyOfChickenBurger + QtyOfChickenBurgerMeal + QtyOfCheeseBurger);
lblDisplayCostOfMeals.setText(Integer.toString(sum));
String x = String.valueOf(comboBox.getSelectedItem());
if (x == "Sprite") {
lblDisplayCostOfDrinks.setText(Integer.toString(spriteCost));
} else if (x == "Select the drink") {
lblDisplayCostOfDrinks.setText("0");
} else if (x == "Coka Cola") {
lblDisplayCostOfDrinks.setText(Integer.toString(cokaColaCost));
} else if (x == "Pepsi") {
lblDisplayCostOfDrinks.setText(Integer.toString(pepsiCost));
} else if (x == "Lemon juce") {
lblDisplayCostOfDrinks.setText(Integer.toString(lemonJuceCost));
}
}
});

This code is wrong
if ((textField.getText().equals(null))) {
QtyOfChickenBurger = Integer.parseInt(textField.getText())*0;
}
if the textField.getText() is null then you can not parse the null into Integer. In addition, you multiply 0 with a number for what? => just set it to 0.
Change it to
if (textField.getText()==null || textField.getText().equals("")){
QtyOfChickenBurger = 0;
}

I presume you are using Swing JTextField which is a JTextComponent.
getText is returning a String therefore, you will need to check if its null or empty, before parsing it to int later on.
There are few ways of checking it, !textField.getText().isEmpty() and textField.getText() != null
Personally, i would use Commons Lang library StringUtils and just check if the string isBlank(textField.getText())
Additionally you should validate the input, as well You can use the mentioned library and use StringUtils.isNumeric() in your if statement.

First of all textField.getText().equals(null) will never work this only throws a NullPointerException better use textField.getText()==null.
Because the user can enter anything in the TextField you need to validate the input or create a try-catch-block.
The best way would to create a help method to parse the numbers, for example:
public static int readInteger(String text, int defaultValue) {
if(text == null)
return defaultValue;
try {
return Integer.parseInt(text);
} catch (NumberFormatException nfe) {
return defaultValue;
}
}
By the way don't compare Strings with x == "Pepsi" only when you want to check if the String is null.
Read: How do I compare strings in Java?

I am assuming that user can write what he want in that textfield so u should also take care when textfield have a value like 'asd';
String QtyOfChickenBurgerAsString =textField.getText();
Integer QtyOfChickenBurger=null;
try{
QtyOfChickenBurger = Integer.valueOf(QtyOfChickenBurgerAsString);
}catch(Exception ex){
System.out.println(" this is not a number ...do whatever u wanna do");
}
if (QtyOfChickenBurger!=null){
System.out.println("integer value of field text "+QtyOfChickenBurger);
}
I suggest create variables with starting letter in lower case ,and when you compare using equals use the constant first.Also you could find a better solution by using components which accept only numbers in their text.

As of java 9, the Object class has a convenience method for handling null values and it is found in java.util.
public static String processEmployee(String fullName){
// if fullName is null then second argument is returned,otherwise fullName is
String name = Objects.requireNonNullElse(fullName, "empty");
// the processing goes here ...
return name;
}

Related

If-else with two possible ways

Could you please help me find a solution for my code? I'm making a new Android app in which I need to make some calculations and the scenario is the following:
There are four fields to be calculated. Two EditText (number decimal) field are obligatory and the other two are optional, BUT, if the optional fields are filled, then it needs to be in the calculation, otherwise only the obligatory fields will be used.
Right now I'm totally OK with calculating the obligatory fields but when I try some if-else clause to include the optional fields in the calculation, the app goes bananas.
I'm not sure where I should make this two-step option, if I should use boolean to check the option field condition, if I just keep using if-else...
The problem is not the calculatin itself, but having two ways for the code to follow: One using only the obligatory fields if nothing else is inserted and the other one using all four fields.
Thanks everyone!
Code below is only using the two obligatory fields.
public void calcularResultado(View view) {
//check for blank values in obligatory fields
if (editGasolina.length() == 0) {
editGasolina.setError("Insira o valor");
}
if (editEtanol.length() == 0) {
editEtanol.setError("Insira o valor");
//runs the code
} else {
double valorGasolina = Double.parseDouble(editGasolina.getText().toString());
double valorEtanol = Double.parseDouble(editEtanol.getText().toString());
double valorResultado = valorEtanol / valorGasolina;
double porcentagem = (valorResultado) * 100;
String valorResultadoTexto = Double.toString(porcentagem);
valorResultadoTexto = String.format("%.2f", porcentagem);
if (valorResultado >= 0.7) {
textResultado.setText("GASOLINA");
textRendimento.setText(valorResultadoTexto + "%");
} else {
textResultado.setText("ETANOL");
textRendimento.setText(valorResultadoTexto + "%");
}
You almost got it. What happens now, since you have an if-if-elseconstruction, it considers the first if statement to be seperate from the if-else block below. That is to say, if editEtanol.length() == 0 evaluates to false, it will execute the else block below, even if editGasolina.length() == 0 evaluates to true.
Changing the line if (editEtanol.length() == 0) { to else if (editEtanol.length() == 0) { should already help alot. Hope that helps!
public void calcularResultado(View view) {
//check for blank values in obligatory fields
if (editGasolina.length() == 0) {
editGasolina.setError("Insira o valor");
}
if (editEtanol.length() == 0) {
editEtanol.setError("Insira o valor");
//runs the code
} else {
double valorGasolina = Double.parseDouble(editGasolina.getText().toString());
double valorEtanol = Double.parseDouble(editEtanol.getText().toString());
boolean optionalField1Used = optionalEditText1.length() != 0;
boolean optionalField2Used = optionalEditText2.length() != 0;
double valorResultado = 0;
if (!optionalField1Used && !optionalField2Used) {
valorResultado = valorEtanol / valorGasolina;
} else if (optionalField1Used && !optionalField2Used) {
valorResultado = //some other calculation
} else if (!optionalField1Used && optionalField2Used) {
valorResultado = //yet another calculation
} else {
valorResultado = //calculation if both optional fields used
}
double porcentagem = (valorResultado) * 100;
String valorResultadoTexto = Double.toString(porcentagem);
valorResultadoTexto = String.format("%.2f", porcentagem);
if (valorResultado >= 0.7) {
textResultado.setText("GASOLINA");
textRendimento.setText(valorResultadoTexto + "%");
} else {
textResultado.setText("ETANOL");
textRendimento.setText(valorResultadoTexto + "%");
}
Let us assume that the optional fields are called edit1 and edit2. I also assume that in order to use the alternative computation, both optional values must be present.
To enhance code clarity, I would define two Boolean variables to explicitly indicate whether the mandatory and optional fields have values. Something like the following.
public void calcularResultado(View view) {
var mandatoryValues = true;
var optionalValues = false;
if (editGasolina.length() == 0 {
editGasolina.setError("Insira o valor");
mandatoryValues = false;
}
if (editEtanol.length() == 0 {
editEtanol.setError("Insira o valor");
mandatoryValues = false;
}
if (edit1.length() > 0 && edit2.length() > 0) {
optionalValues = true;
}
if (mandatoryValues) {
if (optionalValues) {
// do alternative computation
} else {
// do computation for mandatory values only
}
}
}
Note that if either mandatory value is absent, no computation is performed.
Hope it helps - Carlos

How to Make Program flow control jump back to a former loop in java?

So I have written a code that allows a user to find a word in a TextArea. I have nearly succeeded but for one thing. here, I will show you all the code and tell my problem.
if(ta.getText().length() != 0 && t1.getText().length() != 0)
{
char c1[] = ta.getText().trim().toCharArray();
char c2[] = t1.getText().trim().toCharArray();
for(int i=startFlag;i<c1.length;i++)
{
if(c1[i]==c2[0])
{
start = i;
break;
}
}
k=start;
for(int i=0;i<c2.length;i++)
{
if(c2[i] != c1[start++])
{
}
else
countFlag++;
}
if(countFlag==c2.length)
{
ta.select(k,c2.length);
startFlag++;
}
}
For reference, ta is the TextArea and t1 is the TextField where the user enters a word to find. i have a problem in the second for loop. What should I write in the if () block there so that whenever c2[i] != c1[start++] the control is shifted to the first for loop, that would again determine the value of start?
Create a method to get "start" that you can then call whenever you want.
if(ta.getText().length() != 0 && t1.getText().length() != 0)
{
char c1[] = ta.getText().trim().toCharArray();
char c2[] = t1.getText().trim().toCharArray();
k=getStart(startFlag, c1.length);
for(int i=0;i<c2.length;i++)
{
if(c2[i] != c1[start++])
{
start = getStart(startFlag, c1.length);
}
else
countFlag++;
}
if(countFlag==c2.length)
{
ta.select(k,c2.length);
startFlag++;
}
}
And getStart() is:
public int getStart(int startFlag, int length) {
for(int i=startFlag;i<length;i++)
{
if(c1[i]==c2[0])
{
return i;
}
}
}
You may need different inputs to getStart(), but hopefully this gets across the general idea.
The way your code is set up right now, what you're asking for is impossible. To do what you're asking, you'll need to refactor your current code into different methods. More specifically, you'll need to put the for loops into their own methods and then call these methods.
So what you would need to do is make a separate method for the for loop.
public static int startForLoop(int i) {
for(int i=startFlag;i<c1.length;i++)
{
if(c1[i]==c2[0])
{
start = i;
break;
}
}
}
Then you can just call startForLoop(0) initially and in the 2nd for loops if statment:
if(c2[i] != c1[start++])
{
startForLoop(start+1)
}
This will continue the for loop where it left off. If you need to run the 2nd for loop again then you have to make a separate method for it as well and basically place both of them in a while loop that continues till you find the result you want in the 2nd for loop.
May be this code piece help you what you are looking for.
Basically it moves along with the string to be searched in keeping in mind the index of the string to be searched for.
Sorry but i have implemented it in java, but the notion is same and the result returned is the best what i got.you must give it a try!
private static String searchString(String searchIN,String searchFOR){
if (searchFOR != "") {
int index = searchIN.toUpperCase().indexOf(searchFOR.toUpperCase());
String before = "";
String highlighted = "";
String after = "";
while (index >= 0) {
int len = searchFOR.length();
before = searchIN.substring(0, index);
highlighted = "\"" + searchFOR + "\"";//do what ever you want to do with searched string
after = searchIN.substring(index + len);
searchIN = before + highlighted + after;
index = searchIN.toUpperCase().indexOf(searchFOR.toUpperCase(), index + highlighted.length());
}
}
return searchIN;
}

Trying to verify an index number from another method

The first two methods are chunks out of my GUI programme. There are various text fields that allow me input data and then buttons on the GUI take this data and call different methods.
public String getTenant()
{
String theTenant = (tenantsNameText.getText());
return theTenant;
public int getPropertyNumber()
{
int propertyNumber = -1;
try{
propertyNumber = Integer.parseInt(propertyNumberText.getText());
if (properties.size() == 0){
propertyNumber = -1;
}
if (propertyNumber < 0 && propertyNumber >= properties.size()){
propertyNumber = -1;
}
}
catch(NumberFormatException exception){
}
return propertyNumber;
}
In this method I to take the data from the text field of "getTenant" and the data from the text field of "getPropertyNumber". What I'm not sure how to do is check if the property number is -1 or not, and this needs to be verified in the method "addTenant".
public void addTenant()
{
}
I possibly didn't ask the question right, but i figured it out with some help from a colleague.
public void addTenant()
{
int index = getPropertyNumber();
String newTenant = getTenant();
if(index != -1){
Property property = properties.get(index);
if(property instanceof PropertyToLet){
PropertyToLet propertyToLet = (PropertyToLet) property;
propertyToLet.addTenant(newTenant);
}
}
}

How can I check for previous elements and the elements added on to an arraylist in java and do error checks

I have a code that atm checks if the array list has reached the size or not, if no I want it to to perform checks before adding anything else to the list. I have attempted it but cannot figure out why it does not work. below is my method.
private static void addToArrayList(String fruit, double no1, int no2, int no3) throws Exception {
try {
if (arraysList.size() <= 5) {
int count = 0;
for (StoringArray item : arraysList)
if (item.equals("Apple")) {
++count;
if (count > 2)
throw new IllegalArgumentException( "You cannot add more than 2 apples." ); //Instead of this I want a Joption pane pop up to give this error if it applies, but at the moment I am not sure but this code with the current code I have is not working.
}
{
if ( arraysList.get( arraysList.size() - 1 ).equals("Banana") )
throw new IllegalArgumentException( "You have just added this please add something else and then add this if you want." ); }
arraysList.add(new StoringArray(fruit, no1, no2, no3));
}else{
JOptionPane.showMessageDialog(contentPane, "You cannot added mroe than 6 elements.");
}
} catch (Exception e) {
e.printStackTrace();
}
}
I want the error messages to appear in a Joption Pane and I want to check the following errors;
Say the list includes Apples, Bananas, Oranges, PineApples, Grapes
1; I want to check whether the user given parameters no1, no2 and no3 meet the conditon I want i.e.
for (StoreCommands item : commandsList)
if (item.equals("Apple")) {
}no1 need to be greater then 0, no2 needs to be less than 10 and no 3 needs to be less than 15.
2; If user tries to add two apples together in any order it should not be allowed, directly after one another.
3; If the user adds 2 Oranges, they should not be allowed and error message saying this should come up in JOption Pane message box.
If all the conditions are the array values get added to the array list. Thanks I hope I explained myself properly, I have been working on this problem for ages and cannot figure it out for some reason. Thanks again.
----------------edited-----------------with class that stores the arrayList.
public class StoreCommands {
public String toString(){
return Name + " " + Number1 + " " + Number2 + " " + Number3;
}
private String Name;
private int Number1;
private int Number2;
private int Number3;
public String getCommand() {
return Name;
}
public double getcommandNOS() {
return Number1;
}
public int getcommandVLW() {
return Number2;
}
public int getcommandVRW() {
return Number3;
}
public StoringArray(String fruitsNames, double fno1, int fno2, int fno3) throws Exception{
Name = fruitsNames;
Number1 = (int) fno1;
Number2 = fno1;
Number3 = fno3;
}
}
There are also some problems in your StoreCommands (?StoringArray) class and it doesn't compile.
1) The constructor is called StoringArray while the class is called StoreCommands.
2) You shouldn't accept a double value as second parameter and cast it to an int.
3) "Number2 = fno1;" inside the constructor should be "Number2 = fno2;" instead
4) You cannot compare your StoreCommands instance to a String value using equals. You need to compare to the String returned from the getCommand() method:
if (item.getCommand().equals("Apple"))
no1 need to be greater then 0, no2 needs to be less than 10 and no 3 needs to be less than 15. 2; If user tries to add two apples together in any order it should not be allowed, directly after one another. 3; If the user adds 2 Oranges, they should not be allowed and error message saying this should come up in JOption Pane message box.
perhaps something like this would do the job:
public static String getErrorMessage(List<StoreCommands> commands, String fruitsName, int no1, int no2, int no3) {
if (no1 <= 0 || no2 >= 10 || no3 >= 15) {
return "Some Error message...";
}
String previous = null;
int orangeCount = 0;
for (StoreCommands c : commands) {
if (fruitsName.equals("Apple") && previous != null && previous.equals("Apple")) {
return "Some Error message...";
} else if (c.getCommand().equals("Orange")) {
orangeCount++;
}
previous = c.getCommand();
}
return fruitsName.equals("Orange") && orangeCount == 1 ? "Some Error message" : null;
}
your class name is StoreCommands
but you have declared constructor named StoringArray
public StoringArray(String fruitsNames, double fno1, int fno2, int fno3) throws Exception
{
Name = fruitsNames;
Number1 = (int) fno1;
Number2 = fno1;
Number3 = fno3;
}
replace this by
public StoreCommands(String fruitsNames, double fno1, int fno2, int fno3) throws Exception
{
Name = fruitsNames;
Number1 = fno1; //you do not need to cast int because both are int
Number2 = fno1;
Number3 = fno3;
}
in for loop change the conditional logic
for (StoringArray item : arraysList)
if (item.getCommand().equals("Apple"))
{
}
.. it should works now if your other logic and code is ok

In Java/Swing, is there a way to legally "attempt to mutate in notification"?

I was wondering if there is some sort of magic I can use to get around an IllegalStateException and allow a JTextField to "attempt to mutate in notification", or in other words to set its own text if its listener is triggered.
For your information, I am trying to program an auto-complete function which returns the most likely match in a range of 12 enums in response to a user's input in the JTextField.
Here is the code sample. You'll have to pardon my clumsy algorithm which creaks out enum results. I've highlighted the code which produces the exception with a comment:
jtfElement1.addCaretListener(new CaretListener() {
#Override
public void caretUpdate(CaretEvent e) {
String s = jtfElement1.getText();
int[] attributes = new int[13];
// iterate through each enum
for (BaseEnumAttributes b: BaseEnumAttributes.values()) {
// iterate through the length of the current text in jtfElement1
for (int i = 0; i < s.length(); i++) {
if (s.length() <= b.toString().length()) {
if (b.toString().charAt(i) == s.charAt(i)) {
// increase the number of "hits" noted for that enum
attributes[b.ordinal()] = attributes[b.ordinal()] + 1;
}
}
}
}
int priorC = 0;
int rightC = 0;
// iterate through the "array" of enums to find the highest score
for (int j = 0; j < attributes.length; j++) {
if (attributes[j] > priorC) {
priorC = attributes[j];
rightC = j;
}
}
if (!s.equals("")) {
// assign to b the Enum corresponding to the "array" with highest score
BaseEnumAttributes b = BaseEnumAttributes.values()[rightC];
iController.updateInputElement1String(b.toString());
// THIS TRIGGERS EXCEPTION
jtfElement1.setText(b.toString());
}
}
});
You are probably better off using a document filter or a custom document.
What are other listeners expected to see if the document doesn't stay the same during event dispatch?
Use SwingUtilities.invokeLater() placing all the modifications there
Maybe you can delay the setText() with a Thread to run after caretUpdate() has terminated.
i'm found on the same problem but i found an easy solution:
lock the caretUpdate() by a boolean if(false) while u'r setting the text to the jTextField than unlock it after . . something like this:
boolean caret = true;
private void listValueChanged(javax.swing.event.ListSelectionEvent evt) {
caret = false;
name.setText((String)list.getSelectedValue());
caret = true;
}
private void nameCaretUpdate(javax.swing.event.CaretEvent evt) {
if(caret){
model = new DefaultListModel();
this.fillList(name.getText());
list.setModel(model);
}
}
Create a custom Document and override insertString( )
filenameText = new JTextField(new FilenameDocument(), "", 0);
...
/**
* document which adds .xml extension if not specified
*
*/
private class FilenameDocument extends PlainDocument {
#Override
public void insertString(int offset, String insertedText, AttributeSet set)
throws BadLocationException {
if (offset == 0) {
insertedText = insertedText.trim( );
}
super.insertString(offset, insertedText, set);
if (filenameText != null) {
final int caretPos = filenameText.getCaretPosition();
String text = filenameText.getText().trim();
if (text.indexOf('.') == -1) {
filenameText.setText(text + ".xml");
filenameText.setCaretPosition(caretPos);
}
}
}
}
Note that calling setText will result in a recursive call to insertString( ), so make sure you have a stopping condition.
I'm surprised no one has answered this, but would'nt you have been better off implementing an editable JSpinner with a SpinnerListModel?

Categories