Replacing each letter with the letter that is in the corresponding position from the end of the English...

Is using a photo reference for pose fair use?

Why doesn't English employ an H in front of Ares?

Conveying the idea of "tricky"

Are my triangles similar?

Does Turkey make the "structural steel frame" for the F-35 fighter?

Can I exit and reenter a UK station while waiting for a connecting train?

Matrix class in C#

For piano scales, should I let go of the previous key before I hit the next one?

What are the advantages to banks being located in the City of London (the Square Mile)?

出かけることにしました - What is the meaning of this?

As a vegetarian, how can I deal with microwaves smelling of meat and fish?

Find Max of successive Similar Values

だけ between two verbs / second verb performing an action on だけ construction

How can I seal 8 inch round holes in my siding?

What's the safest shape for homemade hard-candy

In this scene from the novel, 'The Martian', by Andy Weir, how does Mark Watney store hydrogen made from water in the tank?

Reverse Voltage?

What does "away to insignificance" mean?

How were Kurds involved (or not) in the invasion of Normandy?

LTSpice Zener diode bug?

Is success due to hard work sustainable in academic research?

Are there any Baryons that have quark-antiquark combinations?

How can a stock trade for a fraction of a cent?

What does "he was equally game to slip into bit parts" mean?



Replacing each letter with the letter that is in the corresponding position from the end of the English alphabet


Review of reservoir samplingFinding the length of shortest transformation sequence from start to endSwap Kth node from beginning with Kth node from end in a Linked ListImplementation of stackProgram that moves characters in n steps to the next character in alphabet based on ASCII codeCount patterns that start and end with “1”, with 0's in betweenReplacing all the 'u' with specific character that is given by the userObject-oriented calculatorData structure that retrieves each item with a specified probabilityCount the occurrence of each letter in a file in Java






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty{
margin-bottom:0;
}








3














$begingroup$


I wrote a small program for hyperskill/jetbrains academy to encrypt the message "we found a treasure!" and print only the ciphertext (in lower case) by replacing each letter with the letter that is in the corresponding position from the end of the English alphabet (a→z, b→y, c→x, ... x→c, y →b, z→a) and without replace spaces or the exclamation mark.



I would like code review comments in terms of correct use of java.



package encryptdecrypt;

public class Main {

final static int lower_case_a = 'a';
final static int lower_case_z = 'z';

public static void main(String[] args) {
String s = "we found a treasure!";

StringBuffer reverse = new StringBuffer();

for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);

if ((int)c >= lower_case_a && (int)c <= lower_case_z)
reverse.append((char)(lower_case_z - c + lower_case_a));
else
reverse.append((char) c);
}
System.out.println(reverse.toString());
}
}









share|improve this question










$endgroup$






















    3














    $begingroup$


    I wrote a small program for hyperskill/jetbrains academy to encrypt the message "we found a treasure!" and print only the ciphertext (in lower case) by replacing each letter with the letter that is in the corresponding position from the end of the English alphabet (a→z, b→y, c→x, ... x→c, y →b, z→a) and without replace spaces or the exclamation mark.



    I would like code review comments in terms of correct use of java.



    package encryptdecrypt;

    public class Main {

    final static int lower_case_a = 'a';
    final static int lower_case_z = 'z';

    public static void main(String[] args) {
    String s = "we found a treasure!";

    StringBuffer reverse = new StringBuffer();

    for (int i = 0; i < s.length(); i++) {
    char c = s.charAt(i);

    if ((int)c >= lower_case_a && (int)c <= lower_case_z)
    reverse.append((char)(lower_case_z - c + lower_case_a));
    else
    reverse.append((char) c);
    }
    System.out.println(reverse.toString());
    }
    }









    share|improve this question










    $endgroup$


















      3












      3








      3





      $begingroup$


      I wrote a small program for hyperskill/jetbrains academy to encrypt the message "we found a treasure!" and print only the ciphertext (in lower case) by replacing each letter with the letter that is in the corresponding position from the end of the English alphabet (a→z, b→y, c→x, ... x→c, y →b, z→a) and without replace spaces or the exclamation mark.



      I would like code review comments in terms of correct use of java.



      package encryptdecrypt;

      public class Main {

      final static int lower_case_a = 'a';
      final static int lower_case_z = 'z';

      public static void main(String[] args) {
      String s = "we found a treasure!";

      StringBuffer reverse = new StringBuffer();

      for (int i = 0; i < s.length(); i++) {
      char c = s.charAt(i);

      if ((int)c >= lower_case_a && (int)c <= lower_case_z)
      reverse.append((char)(lower_case_z - c + lower_case_a));
      else
      reverse.append((char) c);
      }
      System.out.println(reverse.toString());
      }
      }









      share|improve this question










      $endgroup$




      I wrote a small program for hyperskill/jetbrains academy to encrypt the message "we found a treasure!" and print only the ciphertext (in lower case) by replacing each letter with the letter that is in the corresponding position from the end of the English alphabet (a→z, b→y, c→x, ... x→c, y →b, z→a) and without replace spaces or the exclamation mark.



      I would like code review comments in terms of correct use of java.



      package encryptdecrypt;

      public class Main {

      final static int lower_case_a = 'a';
      final static int lower_case_z = 'z';

      public static void main(String[] args) {
      String s = "we found a treasure!";

      StringBuffer reverse = new StringBuffer();

      for (int i = 0; i < s.length(); i++) {
      char c = s.charAt(i);

      if ((int)c >= lower_case_a && (int)c <= lower_case_z)
      reverse.append((char)(lower_case_z - c + lower_case_a));
      else
      reverse.append((char) c);
      }
      System.out.println(reverse.toString());
      }
      }






      java






      share|improve this question














      share|improve this question











      share|improve this question




      share|improve this question










      asked 8 hours ago









      georgeliatsosgeorgeliatsos

      1981 gold badge1 silver badge4 bronze badges




      1981 gold badge1 silver badge4 bronze badges

























          2 Answers
          2






          active

          oldest

          votes


















          2
















          $begingroup$

          Some my suggestions about your code: instead of iterating over the string s because you are not using the i index inside your loop you could iterate over the char array from s like below:



          char[] arr = s.toCharArray();
          for (char c : arr) { //here the body }


          Inside the loop you can use Character.isLowerCase method and you can use a ternary operator to append your character to the StringBuffer evaluating if it is a lowercase character or not:



          String s = "we found a treasure!";
          char[] arr = s.toCharArray();
          StringBuffer reverse = new StringBuffer();

          for (char c : arr) {
          char ch = Character.isLowerCase(c) ? (char)(219 - c) : c; //<-- 219 = int('a') + int('z')
          reverse.append(ch);
          }


          Inside the loop I put 219 because it is a const value so it is not useful recalculate it for every iteration of the loop.






          share|improve this answer










          $endgroup$























            1
















            $begingroup$

            With



            final static int lower_case_a = 'a';
            final static int lower_case_z = 'z';


            While it's arguably good that you have 'a' and 'z' stored as variables and not floating around, I don't think they're named well. lower_case_a tells you exactly as much as 'a' itself, so you aren't really gaining much. The purpose of the variable would make for a better name. Also, since those are constants, they should be upper case, and underscore-separated. I'd change those lines to:



            final static int ALPHABET_UPPER_BOUND = 'a';
            final static int ALPHABET_LOWER_BOUND = 'z';


            Also, as mentioned in the above link, Java uses camelCase, not snake_case.





            if ((int)c >= lower_case_a && (int)c <= lower_case_z)
            reverse.append((char)(lower_case_z - c + lower_case_a));
            else
            reverse.append((char) c);


            This has a few notable things:




            • Do not omit braces here. I won't go as far as to say that they should never be omitted, but the cases where it's appropriate to not use them are pretty slim. If you ever make changes to those lines and don't notice that you didn't use braces, at bst you'll need to deal with syntax errors, and at worst you'll get weird behavior that you'll need to debug. Just use them. It costs next to nothing and prevents a range of errors.


            • Instead of writing (int)c in a few places, I'd probably instead save that in a variable.


            • (char) c isn't necessary. c is already a char.


            • You could use a ternary since each branch is just giving its data to append.



            Something closer to:



            int code = c;
            char newChar = (code >= ALPHABET_UPPER_BOUND && code <= ALPHABET_LOWER_BOUND)
            ? (lower_case_z - c + lower_case_a) : c;

            reverse.append(newChar);


            Although whether you'd want to use a ternary here is subjective. That line is a little long.



            I also agree with @dariosicily though. You never use i for anything other than indexing, so you might as well just use a foreach loop and iterate the string directly.






            share|improve this answer










            $endgroup$

















              Your Answer






              StackExchange.ifUsing("editor", function () {
              StackExchange.using("externalEditor", function () {
              StackExchange.using("snippets", function () {
              StackExchange.snippets.init();
              });
              });
              }, "code-snippets");

              StackExchange.ready(function() {
              var channelOptions = {
              tags: "".split(" "),
              id: "196"
              };
              initTagRenderer("".split(" "), "".split(" "), channelOptions);

              StackExchange.using("externalEditor", function() {
              // Have to fire editor after snippets, if snippets enabled
              if (StackExchange.settings.snippets.snippetsEnabled) {
              StackExchange.using("snippets", function() {
              createEditor();
              });
              }
              else {
              createEditor();
              }
              });

              function createEditor() {
              StackExchange.prepareEditor({
              heartbeatType: 'answer',
              autoActivateHeartbeat: false,
              convertImagesToLinks: false,
              noModals: true,
              showLowRepImageUploadWarning: true,
              reputationToPostImages: null,
              bindNavPrevention: true,
              postfix: "",
              imageUploader: {
              brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
              contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/4.0/"u003ecc by-sa 4.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
              allowUrls: true
              },
              onDemand: true,
              discardSelector: ".discard-answer"
              ,immediatelyShowMarkdownHelp:true
              });


              }
              });















              draft saved

              draft discarded
















              StackExchange.ready(
              function () {
              StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f230636%2freplacing-each-letter-with-the-letter-that-is-in-the-corresponding-position-from%23new-answer', 'question_page');
              }
              );

              Post as a guest















              Required, but never shown


























              2 Answers
              2






              active

              oldest

              votes








              2 Answers
              2






              active

              oldest

              votes









              active

              oldest

              votes






              active

              oldest

              votes









              2
















              $begingroup$

              Some my suggestions about your code: instead of iterating over the string s because you are not using the i index inside your loop you could iterate over the char array from s like below:



              char[] arr = s.toCharArray();
              for (char c : arr) { //here the body }


              Inside the loop you can use Character.isLowerCase method and you can use a ternary operator to append your character to the StringBuffer evaluating if it is a lowercase character or not:



              String s = "we found a treasure!";
              char[] arr = s.toCharArray();
              StringBuffer reverse = new StringBuffer();

              for (char c : arr) {
              char ch = Character.isLowerCase(c) ? (char)(219 - c) : c; //<-- 219 = int('a') + int('z')
              reverse.append(ch);
              }


              Inside the loop I put 219 because it is a const value so it is not useful recalculate it for every iteration of the loop.






              share|improve this answer










              $endgroup$




















                2
















                $begingroup$

                Some my suggestions about your code: instead of iterating over the string s because you are not using the i index inside your loop you could iterate over the char array from s like below:



                char[] arr = s.toCharArray();
                for (char c : arr) { //here the body }


                Inside the loop you can use Character.isLowerCase method and you can use a ternary operator to append your character to the StringBuffer evaluating if it is a lowercase character or not:



                String s = "we found a treasure!";
                char[] arr = s.toCharArray();
                StringBuffer reverse = new StringBuffer();

                for (char c : arr) {
                char ch = Character.isLowerCase(c) ? (char)(219 - c) : c; //<-- 219 = int('a') + int('z')
                reverse.append(ch);
                }


                Inside the loop I put 219 because it is a const value so it is not useful recalculate it for every iteration of the loop.






                share|improve this answer










                $endgroup$


















                  2














                  2










                  2







                  $begingroup$

                  Some my suggestions about your code: instead of iterating over the string s because you are not using the i index inside your loop you could iterate over the char array from s like below:



                  char[] arr = s.toCharArray();
                  for (char c : arr) { //here the body }


                  Inside the loop you can use Character.isLowerCase method and you can use a ternary operator to append your character to the StringBuffer evaluating if it is a lowercase character or not:



                  String s = "we found a treasure!";
                  char[] arr = s.toCharArray();
                  StringBuffer reverse = new StringBuffer();

                  for (char c : arr) {
                  char ch = Character.isLowerCase(c) ? (char)(219 - c) : c; //<-- 219 = int('a') + int('z')
                  reverse.append(ch);
                  }


                  Inside the loop I put 219 because it is a const value so it is not useful recalculate it for every iteration of the loop.






                  share|improve this answer










                  $endgroup$



                  Some my suggestions about your code: instead of iterating over the string s because you are not using the i index inside your loop you could iterate over the char array from s like below:



                  char[] arr = s.toCharArray();
                  for (char c : arr) { //here the body }


                  Inside the loop you can use Character.isLowerCase method and you can use a ternary operator to append your character to the StringBuffer evaluating if it is a lowercase character or not:



                  String s = "we found a treasure!";
                  char[] arr = s.toCharArray();
                  StringBuffer reverse = new StringBuffer();

                  for (char c : arr) {
                  char ch = Character.isLowerCase(c) ? (char)(219 - c) : c; //<-- 219 = int('a') + int('z')
                  reverse.append(ch);
                  }


                  Inside the loop I put 219 because it is a const value so it is not useful recalculate it for every iteration of the loop.







                  share|improve this answer













                  share|improve this answer




                  share|improve this answer










                  answered 7 hours ago









                  dariosicilydariosicily

                  7317 bronze badges




                  7317 bronze badges




























                      1
















                      $begingroup$

                      With



                      final static int lower_case_a = 'a';
                      final static int lower_case_z = 'z';


                      While it's arguably good that you have 'a' and 'z' stored as variables and not floating around, I don't think they're named well. lower_case_a tells you exactly as much as 'a' itself, so you aren't really gaining much. The purpose of the variable would make for a better name. Also, since those are constants, they should be upper case, and underscore-separated. I'd change those lines to:



                      final static int ALPHABET_UPPER_BOUND = 'a';
                      final static int ALPHABET_LOWER_BOUND = 'z';


                      Also, as mentioned in the above link, Java uses camelCase, not snake_case.





                      if ((int)c >= lower_case_a && (int)c <= lower_case_z)
                      reverse.append((char)(lower_case_z - c + lower_case_a));
                      else
                      reverse.append((char) c);


                      This has a few notable things:




                      • Do not omit braces here. I won't go as far as to say that they should never be omitted, but the cases where it's appropriate to not use them are pretty slim. If you ever make changes to those lines and don't notice that you didn't use braces, at bst you'll need to deal with syntax errors, and at worst you'll get weird behavior that you'll need to debug. Just use them. It costs next to nothing and prevents a range of errors.


                      • Instead of writing (int)c in a few places, I'd probably instead save that in a variable.


                      • (char) c isn't necessary. c is already a char.


                      • You could use a ternary since each branch is just giving its data to append.



                      Something closer to:



                      int code = c;
                      char newChar = (code >= ALPHABET_UPPER_BOUND && code <= ALPHABET_LOWER_BOUND)
                      ? (lower_case_z - c + lower_case_a) : c;

                      reverse.append(newChar);


                      Although whether you'd want to use a ternary here is subjective. That line is a little long.



                      I also agree with @dariosicily though. You never use i for anything other than indexing, so you might as well just use a foreach loop and iterate the string directly.






                      share|improve this answer










                      $endgroup$




















                        1
















                        $begingroup$

                        With



                        final static int lower_case_a = 'a';
                        final static int lower_case_z = 'z';


                        While it's arguably good that you have 'a' and 'z' stored as variables and not floating around, I don't think they're named well. lower_case_a tells you exactly as much as 'a' itself, so you aren't really gaining much. The purpose of the variable would make for a better name. Also, since those are constants, they should be upper case, and underscore-separated. I'd change those lines to:



                        final static int ALPHABET_UPPER_BOUND = 'a';
                        final static int ALPHABET_LOWER_BOUND = 'z';


                        Also, as mentioned in the above link, Java uses camelCase, not snake_case.





                        if ((int)c >= lower_case_a && (int)c <= lower_case_z)
                        reverse.append((char)(lower_case_z - c + lower_case_a));
                        else
                        reverse.append((char) c);


                        This has a few notable things:




                        • Do not omit braces here. I won't go as far as to say that they should never be omitted, but the cases where it's appropriate to not use them are pretty slim. If you ever make changes to those lines and don't notice that you didn't use braces, at bst you'll need to deal with syntax errors, and at worst you'll get weird behavior that you'll need to debug. Just use them. It costs next to nothing and prevents a range of errors.


                        • Instead of writing (int)c in a few places, I'd probably instead save that in a variable.


                        • (char) c isn't necessary. c is already a char.


                        • You could use a ternary since each branch is just giving its data to append.



                        Something closer to:



                        int code = c;
                        char newChar = (code >= ALPHABET_UPPER_BOUND && code <= ALPHABET_LOWER_BOUND)
                        ? (lower_case_z - c + lower_case_a) : c;

                        reverse.append(newChar);


                        Although whether you'd want to use a ternary here is subjective. That line is a little long.



                        I also agree with @dariosicily though. You never use i for anything other than indexing, so you might as well just use a foreach loop and iterate the string directly.






                        share|improve this answer










                        $endgroup$


















                          1














                          1










                          1







                          $begingroup$

                          With



                          final static int lower_case_a = 'a';
                          final static int lower_case_z = 'z';


                          While it's arguably good that you have 'a' and 'z' stored as variables and not floating around, I don't think they're named well. lower_case_a tells you exactly as much as 'a' itself, so you aren't really gaining much. The purpose of the variable would make for a better name. Also, since those are constants, they should be upper case, and underscore-separated. I'd change those lines to:



                          final static int ALPHABET_UPPER_BOUND = 'a';
                          final static int ALPHABET_LOWER_BOUND = 'z';


                          Also, as mentioned in the above link, Java uses camelCase, not snake_case.





                          if ((int)c >= lower_case_a && (int)c <= lower_case_z)
                          reverse.append((char)(lower_case_z - c + lower_case_a));
                          else
                          reverse.append((char) c);


                          This has a few notable things:




                          • Do not omit braces here. I won't go as far as to say that they should never be omitted, but the cases where it's appropriate to not use them are pretty slim. If you ever make changes to those lines and don't notice that you didn't use braces, at bst you'll need to deal with syntax errors, and at worst you'll get weird behavior that you'll need to debug. Just use them. It costs next to nothing and prevents a range of errors.


                          • Instead of writing (int)c in a few places, I'd probably instead save that in a variable.


                          • (char) c isn't necessary. c is already a char.


                          • You could use a ternary since each branch is just giving its data to append.



                          Something closer to:



                          int code = c;
                          char newChar = (code >= ALPHABET_UPPER_BOUND && code <= ALPHABET_LOWER_BOUND)
                          ? (lower_case_z - c + lower_case_a) : c;

                          reverse.append(newChar);


                          Although whether you'd want to use a ternary here is subjective. That line is a little long.



                          I also agree with @dariosicily though. You never use i for anything other than indexing, so you might as well just use a foreach loop and iterate the string directly.






                          share|improve this answer










                          $endgroup$



                          With



                          final static int lower_case_a = 'a';
                          final static int lower_case_z = 'z';


                          While it's arguably good that you have 'a' and 'z' stored as variables and not floating around, I don't think they're named well. lower_case_a tells you exactly as much as 'a' itself, so you aren't really gaining much. The purpose of the variable would make for a better name. Also, since those are constants, they should be upper case, and underscore-separated. I'd change those lines to:



                          final static int ALPHABET_UPPER_BOUND = 'a';
                          final static int ALPHABET_LOWER_BOUND = 'z';


                          Also, as mentioned in the above link, Java uses camelCase, not snake_case.





                          if ((int)c >= lower_case_a && (int)c <= lower_case_z)
                          reverse.append((char)(lower_case_z - c + lower_case_a));
                          else
                          reverse.append((char) c);


                          This has a few notable things:




                          • Do not omit braces here. I won't go as far as to say that they should never be omitted, but the cases where it's appropriate to not use them are pretty slim. If you ever make changes to those lines and don't notice that you didn't use braces, at bst you'll need to deal with syntax errors, and at worst you'll get weird behavior that you'll need to debug. Just use them. It costs next to nothing and prevents a range of errors.


                          • Instead of writing (int)c in a few places, I'd probably instead save that in a variable.


                          • (char) c isn't necessary. c is already a char.


                          • You could use a ternary since each branch is just giving its data to append.



                          Something closer to:



                          int code = c;
                          char newChar = (code >= ALPHABET_UPPER_BOUND && code <= ALPHABET_LOWER_BOUND)
                          ? (lower_case_z - c + lower_case_a) : c;

                          reverse.append(newChar);


                          Although whether you'd want to use a ternary here is subjective. That line is a little long.



                          I also agree with @dariosicily though. You never use i for anything other than indexing, so you might as well just use a foreach loop and iterate the string directly.







                          share|improve this answer













                          share|improve this answer




                          share|improve this answer










                          answered 1 hour ago









                          CarcigenicateCarcigenicate

                          7,5361 gold badge19 silver badges48 bronze badges




                          7,5361 gold badge19 silver badges48 bronze badges


































                              draft saved

                              draft discarded



















































                              Thanks for contributing an answer to Code Review Stack Exchange!


                              • Please be sure to answer the question. Provide details and share your research!

                              But avoid



                              • Asking for help, clarification, or responding to other answers.

                              • Making statements based on opinion; back them up with references or personal experience.


                              Use MathJax to format equations. MathJax reference.


                              To learn more, see our tips on writing great answers.




                              draft saved


                              draft discarded














                              StackExchange.ready(
                              function () {
                              StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f230636%2freplacing-each-letter-with-the-letter-that-is-in-the-corresponding-position-from%23new-answer', 'question_page');
                              }
                              );

                              Post as a guest















                              Required, but never shown





















































                              Required, but never shown














                              Required, but never shown












                              Required, but never shown







                              Required, but never shown

































                              Required, but never shown














                              Required, but never shown












                              Required, but never shown







                              Required, but never shown









                              Popular posts from this blog

                              Taj Mahal Inhaltsverzeichnis Aufbau | Geschichte | 350-Jahr-Feier | Heutige Bedeutung | Siehe auch |...

                              Baia Sprie Cuprins Etimologie | Istorie | Demografie | Politică și administrație | Arii naturale...

                              Nicolae Petrescu-Găină Cuprins Biografie | Opera | In memoriam | Varia | Controverse, incertitudini...