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 HJIOADH
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);
}
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);
}
For those searching for another solution:
String anyString = "anystring"
Scanner sn = new Scanner(anyString);
sn.useDelimiter("");
while (sn.hasNext()){
char c = sn.next().charAt(0);
System.out.println(c);
// logic for chars...
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.