I'm new in java, so sorry if this is an obvious question.
I'm trying to read a string character by character to create tree nodes.
for example, input "HJIOADH"
And the nodes are H J I O A D H
I noticed that
char node = reader.next().charAt(0); I can get the first char H by this
char node = reader.next().charAt(1); I can get the second char J by this
Can I use a cycle to get all the characters? like
for i to n
node = reader.next().charAt(i)
I tried but it doesn't work.
How I am suppose to do that?
Thanks a lot for any help.
Scanner reader = new Scanner(System.in); System.out.println("input your nodes as capital letters without space and '/' at the end"); int i = 0; char node = reader.next().charAt(i); while (node != '/') {
CreateNode(node); // this is a function to create a tree node
i++;
node = reader.next().charAt(i);
}
To access character of a string in Java, use the charAt() method. The position is to be added as the parameter. String str = "laptop"; Let's find the character at the 4th position using charAt() method.
charAt(int index) To extract a single character from a String, you can refer directly to an individual character via the charAt( ) method. Example 1: Returns the char value at the specified index of this string. The first char value is at index 0.
You only want to next()
your reader once, unless it has a lot of the same toke nrepeated again and again.
String nodes = reader.next();
for(int i = 0; i < nodes.length(); i++) {
System.out.println(nodes.charAt(i));
}
as Braj mentioned you can try reader.toCharArray()
and to then you can easily use the loop
char[] array = reader.toCharArray();
for (char ch : array) {
System.out.println (ch);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With