Encrypter Learn programming Java

Lesson:

More On Classes


Exercise:

Encrypter 43


Objetive:

Create a class "Encrypter" to encrypt and decrypt text.

It will have a "Encrypt" method, which will receive a string and return another string. It will be a static method, so that we do not need to create any object of type "Encrypter".

There will be also a "Decrypt" method.

In this first approach, the encryption method will be a very simple one: to encrypt we will add 1 to each character, so that "Hello" would become "Ipmb", and to decrypt we would subtract 1 to each character.

An example of use might be

string newText = Encrypter.Encrypt("Hola");


Code:

package Encrypter;
import java.util.*;
public class Encrypter
{
	public static String Encrypt(String text)
	{
		int letterInt = 0;
		char letter = ' ';
		String textEncripted = "";
		for (int i = 0; i < text.length(); i++)
		{
			letterInt = (int)text.charAt(i) + 1;
			letter = (char)letterInt;
			textEncripted += String.valueOf(letter);
		}
		return textEncripted;
	}

	public static String Decrypt(String text)
	{
		int letterInt = 0;
		char letter = ' ';
		String textDecripted = "";
		for (int i = 0; i < text.length(); i++)
		{
			letterInt = (int)text.charAt(i) - 1;
			letter = (char)letterInt;
			textDecripted += String.valueOf(letter);
		}
		return textDecripted;
	}
}

public class Main
{
	public static void main(String[] args)
	{
		boolean debug = true;

		String newText = Encrypter.Encrypt("Hola");
		System.out.printf("Text encripted: %1$s" + "\r\n", newText);
		String TextDescripted = Encrypter.Decrypt(newText);
		System.out.printf("Text Decripted: %1$s" + "\r\n", TextDescripted);

		if (debug)
		{
			new Scanner(System.in).nextLine();
		}
	}
}