Exercises Java with Examples-
Practice Exercises Java 4,5 5 302940

Encrypter - Practice Exercises Java


Lesson 7:

More on classes


Exercise 7.4:

Encrypter


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");


Source 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();
		}
	}
}
Exercisey 7.4

Share Now:


Google Ads





Privacy Policy:



Google uses associated advertising companies to serve ads when it visits our website. These companies may use the information they obtain from your visits to this and other websites (not including your name, address, email address, or phone number) to provide you with announcements about products and services that interest you. If you would like to learn more about this practice and know your options to prevent these companies from using this information. Click in... Privacy and Terms of Google.

Cookies

This site uses Google cookies to provide its services, to personalize advertisements and to analyze traffic. Google receives information about your use of this website. More information in... Privacy and Terms of Google.