Im new with java. im getting struggle with printin something, this is my arraylist
arraylist = ['a','u','o','e']
If my arraylist isnt a static length arraylist. How could I print that list into this
"Your Value: au, oe"
Im kinda confused
Thanks for advance
CodePudding user response:
you can simply loop the array and print each character, and when (index 1) % 2 == 0 && i != list.size() -1
, which means it is the 2rd,4th,6th,... element and not the last one, print an extra ,
.
public void printArray() {
List<Character> list = new ArrayList<>(Arrays.asList('a', 'u', 'o', 'e'));
System.out.print("Your Value: ");
for (int i = 0; i < list.size(); i ) {
System.out.print(list.get(i));
if ((i 1) % 2 == 0 && i != list.size() - 1) {
System.out.print(",");
}
}
}
CodePudding user response:
So an array is a datatype that we use to store multiple values in a single variable. Arrays start at index 0 rather than 1. So this means the first element in the array has an index of 0
array = {0, 1, 2, 3, 4}
So, for your example we would want to do this:
System.out.println("Your Value: " arrayList.get(0) arrayList.get(1) "," arrayList.get(2) arrayList.get(3)
Where we say arrayList.get(0)
that is accessing the first letter in the array which is 'a'
CodePudding user response:
You can concatenate String with character " " like this.
System.out.println("Your Value: " arraylist.get(0) arraylist.get(1) ", " arraylist.get(2) arraylist.get(3));
or you can use a smarter way, using static method inside String class called "format" like this:
System.out.println(String.format("Your Value: %s%s, %s%s", arraylist.get(0), arraylist.get(1), arraylist.get(2), arraylist.get(3)));
You can learn more about String.format() reading this post: