user2769708
user2769708

Reputation: 11

How would I print a single index?

So just to give a little direction, Ihave this assignment where I am supposed to print out the reverse of the input. Ex: If someone types in dylan it prints out nalyd. I'm also supposed to accomplish this using for loops and sub strings.

Here's my code:

    Scanner kb = new Scanner (System.in);
    String name;
    System.out.println("What is your name?");
    name = kb.next();
    int x = name.length();
    for (name.substring(x,x); x>-1; x-=1)
    {
        System.out.print(name.substring(x));
    }

This will print out "nanlanylanDylan" but obviously thats not what I want. Just looking for a way to remedy this, I understand I could use other methods like charAt and such but I'm trying to use just substrings.

Upvotes: 0

Views: 148

Answers (2)

dtgee
dtgee

Reputation: 1272

Substring can work much like charAt() if we just substring one character. To do so, we need to get the position of the current letter that we want, and substring that out.

String name;
for (int i = name.length() - 1; i >= 0; i--) {
    System.out.print(name.substring(x, x+1));
}

Note that the first argument to substring() is inclusive, and the second parameter to substring() is exclusive, so we only get one character with parameters (x, x+1).

String name = "John";
name.substring(0, 1); //returns 'J'

Upvotes: 1

Boann
Boann

Reputation: 50041

String.substring(x) returns the entire string starting at position x until the end. The two-argument form String.substring(begin, end) is what you need to chop out a single character. You should also reduce x by 1 initially to be within range. A fixed version of the loop:

int x = name.length() - 1;
for (name.substring(x,x); x>-1; x-=1)
{
    System.out.print(name.substring(x, x + 1));
}

That extra name.substring(x,x); in the for loop initialization isn't doing anything by the way. A fixed and tidied version of the loop:

for (int x = name.length() - 1; x >= 0; x--)
{
    System.out.print(name.substring(x, x + 1));
}

Upvotes: 2

Related Questions