1

I am studying programming 101 with Java and I am really stuck with this assignment:

"Create a program that asks for the user's name and prints it in reverse order. You do not need to create a separate method for this.

Type your name: Paul In reverse order: luaP

Type your name: Catherine In reverse order: enirehtaC"

I can't figure out why my code gives wrong results. Here is my code thus far:

import java.util.Scanner;

public class ReversingName {
    public static void main(String[] args) {
        Scanner reader = new Scanner(System.in);

    System.out.println("Type a name:");
    String name = reader.nextLine();


    int i = name.length();

    while (i > 0){
        char character = name.charAt(i);
        System.out.print(character);
        i--;
    }

}

}

user3080818
  • 21
  • 1
  • 4
  • 3
    prints it in reverse order. `int i = name.length()-1; while (i >= 0){...}` – Braj May 03 '14 at 09:01
  • 2
    Indices start from 0 and go up to .length() - 1. Your program will throw an IndexOutOfBoundsException. – fge May 03 '14 at 09:01

2 Answers2

1

Your last char is not string.length but string.length - 1

int i = name.length() - 1; // you forgot the -1

while (i >= 0) // and the equal sign must be there because if its not you are missing the first letter
{
    char character = name.charAt(i);
    System.out.print(character);
    i--;
}
Lynx
  • 506
  • 2
  • 10
1

Related to Reverse each individual word of "Hello World" string with Java which uses StringBuilder's reverse() method.

Community
  • 1
  • 1
srm
  • 128
  • 9