I wrote some code in Java, but am having trouble making the character output in Console panel all on one line...
Here's the code
import java.util.ArrayList;
import java.util.List;
public class Main {
public static void main(String[] args) {
String sample = ("Hello World!");
List<Character> colors = new ArrayList<>();
for(int i=0;i<sample.length();i ) {
colors.add(sample.charAt(i);
System.out.println(colors);
}
}
}
The out put when I run the code is like this:
[H]
[H, e]
[H, e, l]
[H, e, l, l]
[H, e, l, l, o]
[H, e, l, l, o, ]
[H, e, l, l, o, , W]
[H, e, l, l, o, , W, o]
[H, e, l, l, o, , W, o, r]
[H, e, l, l, o, , W, o, r, l]
[H, e, l, l, o, , W, o, r, l, d]
[H, e, l, l, o, , W, o, r, l, d, !]
Any help greatly appreciated...
CodePudding user response:
colors is a an ArrayList, so when you're running System.out.print(colors), it uses the default toString implementation of ArrayList, which is all elements with commas between them wrapped by[].
if you want to print it as a regular sentence, you can either print it element at a time (colors.foreach(System.out::print)) or concatenate it into a string and print it
CodePudding user response:
Maybe you want
import java.util.ArrayList;
import java.util.List;
public class Main {
public static void main(String[] args) {
String sample = ("Hello World!");
List<Character> colors = new ArrayList<>();
for(int i=0;i<sample.length();i ) {
colors.add(sample.charAt(i);
}
System.out.println(colors);
}
}
CodePudding user response:
If you don't want an array of characters to be printed as separate characters, don't use println(array). Instead, either write a loop to print each character without anything added, or convert to a String.
public class Main {
public static void main(String[] args) {
String sample = ("Hello World!");
for (int i=0; i<sample.length(); i ) {
System.out.print(sample.charAt(i));
}
System.out.println();
}
}
The above in itself is not too useful, since you're not doing anything except taking the string apart and printing each character. But then again, I don't understand your intent. Maybe you want to print strings of increasing length?
public class Main {
public static void main(String[] args) {
String sample = ("Hello World!");
for (int i=2; i<=sample.length(); i ) {
System.out.println(sample.substring(0, i));
}
}
}
In this second example, i is the index of the first character not printed (i.e., one past the end), and since I assume you don't want a zero-length string printed, the counting starts at 2.
