-1

Let's say I have five int variables that are prompted for user input. User keys in the five value and two of those values are 0. I would like to ONLY print out values that are greater than zero.

int v1 = 1;
int v2 = 30;
int v3 = 0;
int v4 = 37;
int v5 = 0;

I would like to write a dynamic print statement that would exclude the int variables with Zero value.

Currently, my print statement displays all values:

System.out.printf("%s %d%n%s %d%n%s %d%n%s %d%n%s %d%n","V1;","v1","V2:","v2","V3:","v3","V4:","v4","V5:","v5");

I tried writing if-else statements but that became very cumbersome.

John Kugelman
  • 349,597
  • 67
  • 533
  • 578

3 Answers3

1

Create a new method printNonZeroVars(Integer... ints).

public static void main(String[] args) {
  int v1 = 1;
  int v2 = 30;
  int v3 = 0;
  int v4 = 37;
  int v5 = 0;
  printNonZeroVars(v1, v2, v3, v4, v5)
}

public void printNonZeroVars(int... ints) {
  for (int i = 0; i < ints.length; i++) {
     if (ints[i] > 0) {
          System.out.printf("V%d%d%n", i, ints[i]);
     }
  }
}
Umar Nawed
  • 38
  • 5
0

I would use an array.
Iterate over the array and with an if you can check whether your current value is 0.

patpatwithhat
  • 335
  • 2
  • 11
0

So a simple way of achieving this would be to use some sort of Array/List.

ArrayList<Integer> list = new ArrayList<Integer>()
// Or as pointed out by David a better way would be to declare the list as
List<Integer> list = new ArrayList<>();
list.add(5);
list.add(1);
list.add(0);
....

Once you have the list you can use a loop to loop through the list and do relevant checks - something like this

String str = "";
for(int i=0; i<list.size(); i++) {
   if(list.get(i) == 0) {
       continue;
   } 
   str += "v"+i + ":" + Integer.toString(list.get(i));
}
System.out.println(str);

Its pseudo but should give you a good head start :)

Maciej Cygan
  • 5,351
  • 5
  • 38
  • 72
  • You should declare your lists as `List`, not `ArrayList`. [Program to the interface, not the implementation](https://stackoverflow.com/questions/383947/what-does-it-mean-to-program-to-an-interface/384067). And there's no need to repeat the generic type on the right-hand side; you can just write `new ArrayList<>()`. There's also no need to explicitly call `Integer.toString`. You can just append the Integer to the String and its toString method will be called. – David Conrad Feb 22 '22 at 17:35
  • @DavidConrad indeed List is more appropriate. I always specify the right-hand side type (a habit I guess). – Maciej Cygan Feb 22 '22 at 18:37