I've been trying to achieve this for a week with no success. I would like the program to print command line arguments in brackets like shown below (in one line):
---------- +++++++++++ --------- ++++++++
- orange - + apricot + - grape - + kiwi +
---------- +++++++++++ --------- ++++++++
- Command line arguments: orange, apricot, grape, kiwi
- the brackets change from - for arguments with even indexes and + for arguments with odd indexes
But my code prints:
----------
- orange -
----------
+++++++++++
+ apricot +
+++++++++++
---------
- grape -
---------
++++++++
+ kiwi +
++++++++
My code:
public class A2 {
public static void main(String[] args) {
for (int i = 0; i < args.length; i++) {
//1.line
if (i % 2 == 0) {
System.out.println("-".repeat(args[i].length()+4));
} else {
System.out.println("+".repeat(args[i].length()+4));
}
//2.line
if (i % 2 == 0) {
System.out.printf("- %s -\n", args[i]);
} else {
System.out.printf("+ %s +\n", args[i]);
}
//3.line
if (i % 2 == 0) {
System.out.println("-".repeat(args[i].length()+4));
} else {
System.out.println("+".repeat(args[i].length()+4));
}
}
}
}
I tried different print methods, like System.out.print()
and getting rid of \n
, but it only messes up the brackets around words, so I believe I have to do something at the for
loop level, but I am a complete java newbie and I am lost. I thought about maybe adding another variable to solve the problem, but I can't wrap my brain around how to do that in this case and whether it will even solve the problem.