This site requires JavaScript, please enable it in your browser!
Greenfoot back
Astralman
Astralman wrote ...

2016/12/8

How make it display text in reverse?

Astralman Astralman

2016/12/8

#
public class Colors extends World
private String[] green=
    {"G","r","e","e","n" };


----

public void board()
    { 
       for(int i = 1; i < green.length; i++) {
            text("green");

        }
I want it to display green in reverse, like "NEERG" But I don't want to write "neerg". Is there a string+loop for this?
danpost danpost

2016/12/8

#
This should work:
{
    private String green = "GREEN";

    public void board()
    {
        String reverse = "";
        for (char c : green.toCharArray()) reverse = c+reverse;
        System.out.println(reverse);
    }
Astralman Astralman

2016/12/10

#
It says cannot find symbol for "toCharArray" I don't need the square brackets on "private string"?
Super_Hippo Super_Hippo

2016/12/11

#
You have to add the { at the beginning of the class (after line 1 in the first post) and } at the very end. I have no idea why you removed that. The code danpost suggested works fine for me.
danpost danpost

2016/12/11

#
Astralman wrote...
It says cannot find symbol for "toCharArray" I don't need the square brackets on "private string"?
I used a simple String for the word instead of a String array with each element being a String of length one; then, I used the 'toCharArray' method to create the array you original had (except it is now a Character array -- not a String array). Because it is a simple String, no brackets are used (square or otherwise).
KFGL KFGL

2016/12/12

#
It should work, I checked danpost's code, and it worked perfectly. It might be a java version problem, but I am pretty sure that that function is pretty standard. Are you sure that the green variable is a String? Make sure that you are copying the code exactly. Yes, you do not need the square brackets, because a String is essentially an array of chars, and danpost's code is turning your string into an array of chars, and then reversing that. p.s. I am pretty sure that you could do the same thing with an array of Strings, but danpost's code would be more standard, and a string takes more memory.
Astralman Astralman

2016/12/12

#
It worked. I wrote things wrong. Thanks
You need to login to post a reply.