jueves, 9 de marzo de 2017

Java: Leer una cadena desde consola e imprimirla al reves

Es muy común en las clases de programación de Java el solicitar un programa que lea una cadena desde la consola y luego la imprima al reves. Para ello podemos hacerlo de dos formas, la primera es usar la clase StringBuilder, la segunda es desarrollar un metodo propio. Aquí les dejo un programa en en Java que usa las dos formas.


/*
 * Tutorials
 * Copyright (C) 20017 Roberto Lopez marcos.roberto.lopez@gmail.com
 * 
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 * 
 * Roberto Lopez
 * CDMX, México
 * https://marcosrobertos.blogspot.com
 * Email: marcos.roberto.lopez@gmail.com
 */
 
package com.rlopez.tutorials.string;

import java.util.Scanner;

/**
 *
 * @author Cliente
 */
public class ReverseString {
   public static void main(String args[]){
      System.out.println("Ingresa una palabra [presione enter para confirmar]");
      Scanner scanner = new Scanner(System.in);
      String world = scanner.nextLine();
      //first way create a string builder instance, reverse the same instance
      //of string builder
      System.out.println("Reverse using StringBuilder.reverse(): "
      + (new StringBuilder(world).reverse()));
      //second way use my own method, reverse and return a new instance of
      //string
      System.out.println("Reverse using my owner reverse(): "
      + (ReverseString.reverse(world)));
   }
   
   public static String reverse(String toReverse){
      char characters[] = new char[toReverse.length()];
      int j = 0;
      for(int i = toReverse.length() - 1; i >= 0; i--){
         characters[j++] = toReverse.charAt(i);
      }
      return new String(characters);
   }
}

Salida:

compile-single:
run-single:
Ingresa una palabra [presione enter para confirmar]
Hola buenos días
Reverse using StringBuilder.reverse(): saíd soneub aloH
Reverse using my owner reverse(): saíd soneub aloH