# read int and encrypt it

• 02-02-2013, 12:21 PM
jazzo
hi chaps,I am very new to java and I am reading the deitel and deitel book "java how to program" I would like to do this exercise taken from it, chapter 4 exercise 4.38, in brief: "Write an application that reads a 4 digit int and encrypt it replacing each digit with the result of addin 7 to it and getting the reminder after dividing the new value by 10. Then swap the first digit with the 3rd and swap the second with the fourt, then print the encrypted digit".
Now bearing in mind that I am only allowed to use a while statement (no for loops, no array, no switch and assuming the user enters numbers and not letters) because I haven't done them as yet, this is what I came up with so far, but I got somewhat stuck:

Code:

```//Encrypt.java public class EncryptionTest{         public static void main( String[] args){                         Encryption myNumber = new Encryption();                 myNumber.insertNumber();                 }                        }```
and

Code:

```//Encryption.java import java.util.Scanner; //import java.lang.StringBuffer; public class Encryption{         private int number;//digit inserted by the user         private int numberLenght;//to calculate the length         //private int numberLeft;         private int digit;                 public void insertNumber(){                 //System.out.print("digit is " + number + "\n");                 System.out.print("Insert your 4 digit int to convert and press enter: ");                 Scanner input = new Scanner(System.in);                 number = input.nextInt();                 System.out.printf("You have inserted %d\n", number);                 //String numberToModify = extractNumber();                 extractNumber();                 //System.out.print(numberToModify );                 }         private void extractNumber(){                 //System.out.printf("Digit inserted in previous method %d\n", number);                 int numberLenght = number;                        String fullNumber;                                        while(number > 0){                         //int numberOfDigits += 1;                         digit = number % 10;                                        fullNumber =        encryptNumber(digit);                                                number /= 10;                                System.out.print(fullNumber );                                                                }                         //return fullNumber;                 }                                 private String encryptNumber(int toEncrypt){                         toEncrypt = ((toEncrypt + 7) % 10);                         String theNumber = String.valueOf(toEncrypt);                         //System.out.print(theNumber );                         return theNumber;                         }         }```
So basically I got to the point of reading the int in and encrypt it half way. What I am not entirely sure how to do, is to swap the digits according to the exercise. This becasue as you can see I am encrypting the int digit one by one. the function
Code:

`private String encryptNumber()`
returns the number to
Code:

`private void extractNumber()`
but ideally I should return the number to
Code:

`public void insertNumber(){`
in order to be able to swap the digits (that by now are part of a string). However I am not able to return //return fullNumber; even if I make the due changes because the compiler tells me that the variable hasn't been initialize. ANyway, has anybody got any suggestion please?
thanks
• 02-03-2013, 05:29 AM
Estrella
Re: read int and encrypt it
In reference to swapping the digits, one way could approach it is to encrypt each digit, and save the whole number in 'fullNumber,' and after that switch the digits.

I want to point out line 28:

Code:

`fullNumber =  encryptNumber(digit);`
This line will replace whatever is in 'fullNumber' with whatever 'encryptNumber()' returns. I would look at how to append a new value to 'fullNumber'.
• 02-03-2013, 04:56 PM
jazzo
Re: read int and encrypt it
Quote:

Originally Posted by Estrella
In reference to swapping the digits, one way could approach it is to encrypt each digit, and save the whole number in 'fullNumber,' and after that switch the digits.

I want to point out line 28:

Code:

`fullNumber =  encryptNumber(digit);`
This line will replace whatever is in 'fullNumber' with whatever 'encryptNumber()' returns. I would look at how to append a new value to 'fullNumber'.

Hi thanks for the suggestion. Then I could use the append() method...never used it before. I have read the api and it seems I have to do
Code:

`import java.lang.StringBuffer;`
Also, would I then need to do something like
Code:

```StringBuffer fullNumber = new StringBuffer(""); fullNumber.append(encryptNumber(digit));```
?
thanks. Sorry I am very new to java
• 02-03-2013, 08:05 PM
Estrella
Re: read int and encrypt it
Yes, append() will work. You can also concatenate each digit to the original string ( String Concatenation using Java ).

Regardless of which way you choose to implement it, think about how you will swap the digits once you've encrypted each digit.
• 02-03-2013, 09:46 PM
jazzo
Re: read int and encrypt it
Quote:

Originally Posted by Estrella
Yes, append() will work. You can also concatenate each digit to the original string ( String Concatenation using Java ).

Regardless of which way you choose to implement it, think about how you will swap the digits once you've encrypted each digit.

Well I suppose I will need to get the size of the string first in my case it should be something like
Code:

`fullNumber.length();`
then from what I remember strings are immutable so I will have to create a new string or something like that.
Code:

```string newFullNumber = fullNumber.replace(fullNumber.charAt(2),fullNumber.charAt(0)); string finalNewFullNumber = fullNumber.replace(fullNumber.charAt(3),fullNumber.charAt(1));```
SO create 2 variables with the new strings
• 02-03-2013, 10:32 PM
Estrella
Re: read int and encrypt it
Try it out within your program and let's see how it works.
• 02-03-2013, 11:23 PM
jazzo
Re: read int and encrypt it
No problem, thanks for your help: I guess it will have to be something like this:
Code:

```//Encryption.java import java.util.Scanner; import java.lang.StringBuffer; public class Encryption{         private int number;//digit inserted by the user         private int numberLenght;//to calculate the length         //private int numberLeft;         private int digit;                 public void insertNumber(){                 //System.out.print("digit is " + number + "\n");                 System.out.print("Insert your 4 digit int to convert and press enter: ");                 Scanner input = new Scanner(System.in);                 number = input.nextInt();                 System.out.printf("You have inserted %d\n", number);                 //String numberToModify = extractNumber();                 extractNumber();                 //System.out.print(numberToModify );                 }         private void extractNumber(){                 //System.out.printf("Digit inserted in previous method %d\n", number);                 int numberLenght = number;                        //String fullNumber;                 StringBuffer fullNumber = new StringBuffer("");//new string declaration                 while(number > 0){                         //int numberOfDigits += 1;                                                                                digit = number % 10;                                //fullNumber =        encryptNumber(digit);                         fullNumber.append(encryptNumber(digit));                                number /= 10;                                                                                                        //System.out.print(fullNumber );                                                }                         fullNumber.reverse();//this is because when encrypted the string is printed the other way around                         //swap numbers:                         int stringLength = fullNumber.length();//lenght of string                                                string newFullNumber = fullNumber;                //new string cointaining the old one                                                                                                char ch1 = newFullNumber.charAt(0);//1                         char ch2 = newFullNumber.charAt(1);//2                         char ch3 = newFullNumber.charAt(2);//3 //1                         char ch4 = newFullNumber.charAt(3);//4 //2                         //temp variables                         char tempCh3 = ch3;                         char tempCh4 = ch4;                         //swapping                         newFullNumber.replace(newFullNumber.charAt(2),newFullNumber.charAt(0));                                newFullNumber.replace(newFullNumber.charAt(3),newFullNumber.charAt(1));                         newFullNumber.replace(newFullNumber.charAt(0),tempCh3);                         newFullNumber.replace(newFullNumber.charAt(1),tempCh4);                                                                                        //return fullNumber;                 }                                 private String encryptNumber(int toEncrypt){                         toEncrypt = ((toEncrypt + 7) % 10);                         String theNumber = String.valueOf(toEncrypt);                         //System.out.print(theNumber );                         return theNumber;                         }         }```
?
thanks
• 02-04-2013, 12:18 AM
Estrella
Re: read int and encrypt it
It's hard to be certain a program is correct simply by looking at it. I would get a few values to input, figure out what the output should be, then run your program with the input and see if your program's output matches your expected output. Since returning fullNumber isn't set up right now, you can print out fullNumber, or is it newFullNumber, in the extractNumber() method and fix the other part once you know how our program works.
• 02-04-2013, 10:53 PM
jazzo
Re: read int and encrypt it
mmm, it's returning an error:
Code:

```antobbo@antobbo-xps17-ubuntu:~/Documents/dell xps/My documents/java/tests/encryption\$ javac *.java Encryption.java:37: error: incompatible types                         String newFullNumber = fullNumber;                //new string cointaining the old one                                                                              ^   required: String   found:    StringBuffer 1 error```
I believe it's because I am attempting to copy a variable of type
Code:

`StringBuffer fullNumber`
into one of type String
Code:

`String newFullNumber = fullNumber;`
. But I thought the 2 types were compatible, and also I need that
Code:

`StringBuffer fullNumber`
because I use the append method...
• 02-04-2013, 11:12 PM
Estrella
Re: read int and encrypt it
There should be a method that returns fullNumber as a String instead of a StringBuffer. Check the API, you can use that method when you assign the value of fullNumber to newFullNumber.
• 02-05-2013, 03:25 PM
jazzo
Re: read int and encrypt it
thanks, I guess you're talking about the
Code:

`.toString()`
method? So it should be
Code:

` string newFullNumber = fullNumber.toString();`
? Can't test it right now, but will do that as soon as I get home in a few hours and post the output!
thanks
• 02-05-2013, 05:53 PM
Estrella
Re: read int and encrypt it
Capitalize the 's' on String and it should get rid of that problem. Let's see how it goes!
• 02-06-2013, 08:07 PM
jazzo
Re: read int and encrypt it
Woah! it works! here's the finished version:
Code:

```//Encryption.java import java.util.Scanner; import java.lang.StringBuffer; public class Encryption{         private int number;//digit inserted by the user         private int numberLenght;//to calculate the length         //private int numberLeft;         private int digit;                 public void insertNumber(){                 //System.out.print("digit is " + number + "\n");                 System.out.print("Insert your 4 digit int to convert and press enter: ");                 Scanner input = new Scanner(System.in);                 number = input.nextInt();                 System.out.printf("You have inserted %d\n", number);                 //String numberToModify = extractNumber();                 extractNumber();                 //System.out.print(numberToModify );                 }         private void extractNumber(){                 //System.out.printf("Digit inserted in previous method %d\n", number);                 int numberLenght = number;                        //String fullNumber;                 StringBuffer fullNumber = new StringBuffer("");//new string declaration                 while(number > 0){                         //int numberOfDigits += 1;                                                                                digit = number % 10;                                //fullNumber =        encryptNumber(digit);                         fullNumber.append(encryptNumber(digit));                                number /= 10;                                                                                                        //System.out.print(fullNumber );                                                }                         fullNumber.reverse();//this is because when encrypted the string is printed the other way around                         //swap numbers:                         int stringLength = fullNumber.length();//lenght of string                                                String newFullNumber = fullNumber.toString();                //new string cointaining the old one                                                                                                char ch1 = newFullNumber.charAt(0);//1                         char ch2 = newFullNumber.charAt(1);//2                         char ch3 = newFullNumber.charAt(2);//3 //1                         char ch4 = newFullNumber.charAt(3);//4 //2                         //temp variables                         char tempCh3 = ch3;                         char tempCh4 = ch4;                         //swapping                         newFullNumber.replace(newFullNumber.charAt(2),newFullNumber.charAt(0));                                newFullNumber.replace(newFullNumber.charAt(3),newFullNumber.charAt(1));                         newFullNumber.replace(newFullNumber.charAt(0),tempCh3);                         newFullNumber.replace(newFullNumber.charAt(1),tempCh4);        System.out.println("The encrypted number is " +  newFullNumber);                                                                        //return fullNumber;                 }                                 private String encryptNumber(int toEncrypt){                         toEncrypt = ((toEncrypt + 7) % 10);                         String theNumber = String.valueOf(toEncrypt);                         //System.out.print(theNumber );                         return theNumber;                         }         }```
thanks for your help. I appreciate the swap code could be written in a more efficient way, couldn't it?
• 02-06-2013, 08:52 PM
Estrella
Re: read int and encrypt it
Well, since you extract each character (line 39 - 42), you can concatenate (+) the characters together to make up a new String.

You can't save a char as a String directly, but you can change the character to a string using an empty string, "". So, starting with "", you can concatenate each character in the new order and save it to newFullNumber. This should replaces line 44-50.

Does that make sense? I'm not sure if I explained that clearly.
• 02-06-2013, 09:17 PM
Estrella
Re: read int and encrypt it
Number two is an example of what I'm talking about: How to convert Char to String in Java with Example
• 02-07-2013, 12:02 AM
jazzo
Re: read int and encrypt it
I see thanks, I was more worried about the actual swap thing that seemed a bit clunky
Code:

``` char ch1 = newFullNumber.charAt(0);//1             char ch2 = newFullNumber.charAt(1);//2             char ch3 = newFullNumber.charAt(2);//3 //1             char ch4 = newFullNumber.charAt(3);//4 //2             //temp variables             char tempCh3 = ch3;             char tempCh4 = ch4;             //swapping             newFullNumber.replace(newFullNumber.charAt(2),newFullNumber.charAt(0));             newFullNumber.replace(newFullNumber.charAt(3),newFullNumber.charAt(1));             newFullNumber.replace(newFullNumber.charAt(0),tempCh3);             newFullNumber.replace(newFullNumber.charAt(1),tempCh4); System.out.println("The encrypted number is " +  newFullNumber);```
but if you think it is ok then, fine : - )
• 02-07-2013, 07:55 PM
Estrella
Re: read int and encrypt it
I was talking about that as well, but I wasn't clear.

Since you extracted each character (line 1-4 in the post above), you can concatenate the characters into the encrypted string. This should be a one-line operation, which will replace lines 6-12 in the code above. It will look something like this (of course you'll have to arrange your characters into the right order):

Code:

`String code = "" + char1 + char2 + char3 + char4;`
Using the empty string ("") changes the 'char's into Strings.

Let me know I can clarify anything.