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.
CodePudding user response:
I would use an array.
Iterate over the array and with an if you can check whether your current value is 0.
CodePudding user response:
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(Integer... ints) {
for (int i = 0; i < ints.length; i ) {
if (ints[i] > 0) {
System.out.printf("V%d%d%n", i, ints[i]);
}
}
}
CodePudding user response:
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 :)