lundi 6 juin 2016

Creating a string with nested if statements in java

I am currently working on a project to improve cash management at my store. At one point in my program I have a string that gets created based on what bills and how many get dropped into the safe at night. I originally wrote a block of nested if statements to get this to work, however it did not work and I can see why. Here is the nested statement I wrote:

//this nested block does not work but I want to try and find a way to make it work.
  /*if(hundred == 0){
     if(fifty == 0){
        if(twenty == 0){
           if(ten == 0){
              if(five == 0){
                 dropString = String.format("Drop(%d-$1's)%s", one, initials);
              }
              else
                 dropString = String.format("Drop(%d-$5's, %d-$1's)%s", five, one, initials);
           }
           else dropString = String.format("Drop(%d-$10's, %d-$5's, %d-$1's)%s", ten, five, one, initials);
        }
        else dropString = String.format("Drop(%d-$20's, %d-$10's, %d-$5's, %d-$1's)%s", twenty, ten, five, one, initials);
     }
     else dropString = String.format("Drop(%d-$50's, %d-$20's, %d-$10's, %d-$5's, %d-$1's)%s", fifty, twenty, ten, five, one, initials);
  }
  else dropString = String.format("Drop(%d-$100's, %d-$50's, %d-$20's, %d-$10's, %d-$5's, %d-$1's)%s", hundred, fifty, twenty, ten, five, one, initials);

I want the string to only include values greater than zero, which you can see using this method will obviously not work because it will include all blocks after one statement is greater than zero. I have found something that works for what I want, but isn't the best if the variable 'hundred' is zero. This is what I have come up with that works:

  if(hundred != 0)
     dropString += String.format("%d-$100's", hundred);
  if(fifty != 0)
     dropString += String.format(", %d-$50's", fifty);
  if(twenty != 0)
     dropString += String.format(", %d-$20's", twenty);
  if(ten != 0)
     dropString += String.format(", %d-$10's", ten);
  if(five != 0)
     dropString += String.format(", %d-$5's", five);
  if(one != 0)
     dropString += String.format(", %d-$1's", one);

  dropString += String.format(")%s", initials);

When 'hundred' is equal to zero, the string is something like this "Drop(, 16-$20's)RE" My question is this, is there a way to use nested statements or a good way to remove the leading", " when 'hundred' is zero? (I want a way that doesn't involve an if statement for every single possible combination of values equal to or greater than zero)

Aucun commentaire:

Enregistrer un commentaire