Question

In: Computer Science

Please convert this code written in Python to Java: import string import random #function to add...

Please convert this code written in Python to Java:

import string
import random

#function to add letters
def add_letters(number,phrase):
   #variable to store encoded word
   encode = ""
  
   #for each letter in phrase
   for s in phrase:
       #adding each letter to encode
       encode = encode + s
       for i in range(number):
           #adding specified number of random letters adding to encode
           encode = encode + random.choice(string.ascii_letters)
   #returns encoded word
   return encode
#function to remove letters
def remove_letters(number,phrase):
   #variable to store decoded word
   decode = ""
  
   #iterating each letter in phrase
   for i in range(len(phrase)):
       #if i % number + 1 is zero
       if i % (number + 1) == 0:
           #adding letters in specified position to decode
           decode = decode + phrase[i]
   #returns decoded word
   return decode

#repeat until user wants to quit
while True:
   print("")
   #prompt for user option
   userOption = input("(e)ncode, (d)ecode, (q)uit: ")
  
   #if option is encode
   if userOption == "e":
       #prompt for number
       number = int(input("Enter a number between 1 and 5: "))
      
       #repeat until number is valid
       while True:
           #if number is valid
           if number >= 1 and number <= 5:
               break
           #if number is not valid
           else:
               print("Try Again...")
              
               #prompt for number
               number = int(input("Enter a number between 1 and 5: "))
      
       #prompt for phrase to encode
       phrase = input("Enter a phrase to encode: ")
      
       #calling function add_letters and printing encoded word
       print("Your encoded word is: "+add_letters(number,phrase))
  
   #if option is decode
   elif userOption == "d":
       #prompt for number
       number = int(input("Enter a number between 1 and 5: "))
      
       #repeat until number is valid
       while True:
           #if number is valid
           if number >= 1 and number <= 5:
               break
           #if number is not valid
           else:
               print("Try Again...")
              
               #prompt for number
               number = int(input("Enter a number between 1 and 5: "))
      
       #prompt for phrase to decode
       phrase = input("Enter a phrase to decode: ")
      
       #calling function remove_letters and printing decoded word
       print("Your decoded word is: "+remove_letters(number,phrase))
      
   #if option is quit
   elif userOption == "q":
       break
      
   #if option is wrong option
   else:
       print("Try Again...")

Solutions

Expert Solution

Here is the converted code for this problem in Java. Comments are included, go through it, learn how things work and let me know if you have any doubts or if you need anything to change. If you are satisfied with the solution, please rate the answer. Thanks

// EncodeDecode.java

import java.util.Scanner;

public class EncodeDecode {

      // function to add letters

      static String add_letters(int number, String phrase) {

            // variable to store encoded word

            String encode = "";

            // variable to store all letters in ascii table

            String letters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";

            // for each letter in phrase

            for (Character c : phrase.toCharArray()) {

                  // adding each letter to encode

                  encode = encode + c;

                  for (int i = 0; i < number; i++) {

                        // adding specified number of random letters adding to encode

                        encode = encode

                                    + letters.charAt((int) (Math.random() * letters

                                                 .length()));

                  }

            }

            // returns encoded word

            return encode;

      }

      // function to remove letters

      static String remove_letters(int number, String phrase) {

            // variable to store decoded word

            String decode = "";

            // iterating each letter in phrase

            for (int i = 0; i < phrase.length(); i++)

                  // if i % number + 1 is zero

                  if (i % (number + 1) == 0) {

                        // adding letters in specified position to decode

                        decode = decode + phrase.charAt(i);

                  }

            // returns decoded word

            return decode;

      }

      public static void main(String[] args) {

            Scanner scanner = new Scanner(System.in);

            // repeat until user wants to quit

            while (true) {

                  System.out.println("\n(e)ncode, (d)ecode, (q)uit: ");

                  // prompt for user option

                  char userOption = scanner.nextLine().toLowerCase().charAt(0);

                  // if option is encode

                  if (userOption == 'e') {

                        // prompt for number

                        System.out.print("Enter a number between 1 and 5: ");

                        int number = Integer.parseInt(scanner.nextLine());

                        // repeat until number is valid

                        while (true) {

                              // if number is valid

                              if (number >= 1 && number <= 5) {

                                    break;

                              }

                              // if number is not valid

                              else {

                                    System.out.println("Try Again...");

                                    // prompt for number

                                    System.out.print("Enter a number between 1 and 5: ");

                                    number = Integer.parseInt(scanner.nextLine());

                              }

                        }

                        // prompt for phrase to encode

                        System.out.print("Enter a phrase to encode: ");

                        String phrase = scanner.nextLine();

                        // calling function add_letters and printing encoded word

                        System.out.println("Your encoded word is: "

                                    + add_letters(number, phrase));

                  }

                  // if option is decode

                  else if (userOption == 'd') {

                        // prompt for number

                        System.out.print("Enter a number between 1 and 5: ");

                        int number = Integer.parseInt(scanner.nextLine());

                        // repeat until number is valid

                        while (true) {

                              // if number is valid

                              if (number >= 1 && number <= 5) {

                                    break;

                              }

                              // if number is not valid

                              else {

                                    System.out.println("Try Again...");

                                    // prompt for number

                                    System.out.print("Enter a number between 1 and 5: ");

                                    number = Integer.parseInt(scanner.nextLine());

                              }

                        }

                        // prompt for phrase to decode

                        System.out.print("Enter a phrase to decode: ");

                        String phrase = scanner.nextLine();

                        // calling function remove_letters and printing decoded word

                        System.out.println("Your decoded word is: "

                                    + remove_letters(number, phrase));

                  }

                  // if option is quit

                  else if (userOption == 'q') {

                        break;

                  } else

                        System.out.println("Try Again...");

            }

      }

}

/*OUTPUT*/

(e)ncode, (d)ecode, (q)uit:

e

Enter a number between 1 and 5: 4

Enter a phrase to encode: hello world

Your encoded word is: hyaemenGpMlhWuYlgfwOoESnt RPQwwiOoqokjttrbwWrlDZTRdofOr

(e)ncode, (d)ecode, (q)uit:

d

Enter a number between 1 and 5: 4

Enter a phrase to decode: hyaemenGpMlhWuYlgfwOoESnt RPQwwiOoqokjttrbwWrlDZTRdofOr

Your decoded word is: hello world

(e)ncode, (d)ecode, (q)uit:

e

Enter a number between 1 and 5: 6

Try Again...

Enter a number between 1 and 5: 1

Enter a phrase to encode: java

Your encoded word is: jdaMvEam

(e)ncode, (d)ecode, (q)uit:

d

Enter a number between 1 and 5: 1

Enter a phrase to decode: jdaMvEam

Your decoded word is: java

(e)ncode, (d)ecode, (q)uit:

q


Related Solutions

can you please convert this python code into java? Python code is as shown below: #...
can you please convert this python code into java? Python code is as shown below: # recursive function def row_puzzle_rec(row, pos, visited):    # if the element at the current position is 0 we have reached our goal    if row[pos] == 0:        possible = True    else:        # make a copy of the visited array        visited = visited[:]        # if the element at the current position has been already visited then...
Can someone please convert this java code to C code? import java.util.LinkedList; import java.util.List; public class...
Can someone please convert this java code to C code? import java.util.LinkedList; import java.util.List; public class Phase1 { /* Translates the MAL instruction to 1-3 TAL instructions * and returns the TAL instructions in a list * * mals: input program as a list of Instruction objects * * returns a list of TAL instructions (should be same size or longer than input list) */ public static List<Instruction> temp = new LinkedList<>(); public static List<Instruction> mal_to_tal(List<Instruction> mals) { for (int...
Please add comments to this code! JAVA Code: import java.text.NumberFormat; public class Item {    private...
Please add comments to this code! JAVA Code: import java.text.NumberFormat; public class Item {    private String name;    private double price;    private int bulkQuantity;    private double bulkPrice;    /***    *    * @param name    * @param price    * @param bulkQuantity    * @param bulkPrice    */    public Item(String name, double price, int bulkQuantity, double bulkPrice) {        this.name = name;        this.price = price;        this.bulkQuantity = bulkQuantity;        this.bulkPrice = bulkPrice;   ...
Python program.  from random import . Write a function called cleanLowerWord that receives a string as a...
Python program.  from random import . Write a function called cleanLowerWord that receives a string as a parameter and returns a new string that is a copy of the parameter where all the lowercase letters are kept as such, uppercase letters are converted to lowercase, and everything else is deleted. For example, the function call cleanLowerWord("Hello, User 15!") should return the string "hellouser". For this, you can start by copying the following functions discussed in class into your file: # Checks...
Please add comments to this code! JAVA code: import java.util.ArrayList; public class ShoppingCart { private final...
Please add comments to this code! JAVA code: import java.util.ArrayList; public class ShoppingCart { private final ArrayList<ItemOrder> itemOrder;    private double total = 0;    private double discount = 0;    ShoppingCart() {        itemOrder = new ArrayList<>();        total = 0;    }    public void setDiscount(boolean selected) {        if (selected) {            discount = total * .1;        }    }    public double getTotal() {        total = 0;        itemOrder.forEach((order) -> {            total +=...
Can you please add comments to this code? JAVA Code: import java.util.ArrayList; public class Catalog {...
Can you please add comments to this code? JAVA Code: import java.util.ArrayList; public class Catalog { String catalog_name; ArrayList<Item> list; Catalog(String cs_Gift_Catalog) { list=new ArrayList<>(); catalog_name=cs_Gift_Catalog; } String getName() { int size() { return list.size(); } Item get(int i) { return list.get(i); } void add(Item item) { list.add(item); } } Thanks!
UML Diagram for this java code //java code import java.util.*; class Message { private String sentence;...
UML Diagram for this java code //java code import java.util.*; class Message { private String sentence; Message() { sentence=""; } Message(String text) { setSentence(text); } void setSentence(String text) { sentence=text; } String getSentence() { return sentence; } int getVowels() { int count=0; for(int i=0;i<sentence.length();i++) { char ch=sentence.charAt(i); if(ch=='a' || ch=='e' || ch=='i' || ch=='o' || ch=='u' || ch=='A' || ch=='E' || ch=='I' || ch=='O' || ch=='U') { count=count+1; } } return count; } int getConsonants() { int count=0; for(int i=0;i<sentence.length();i++)...
CONVERT CODE FROM JAVA TO C# PLEASE AND SHOW OUTPUT import java.util.*; public class TestPaperFolds {...
CONVERT CODE FROM JAVA TO C# PLEASE AND SHOW OUTPUT import java.util.*; public class TestPaperFolds {    public static void main(String[] args)    {        for(int i = 1; i <= 4; i++)               //loop for i = 1 to 4 folds        {            String fold_string = paperFold(i);   //call paperFold to get the String for i folds            System.out.println("For " + i + " folds we get: " + fold_string);        }    }    public static String paperFold(int numOfFolds)  ...
Please convert this java program to a program with methods please. import java.io.*; import java.util.*; public...
Please convert this java program to a program with methods please. import java.io.*; import java.util.*; public class Number{ public static void main(String[] args) {    Scanner scan = new Scanner(System.in); System.out.println("Enter 20 integers ranging from -999 to 999 : "); //print statement int[] array = new int[20]; //array of size 20 for(int i=0;i<20;i++){ array[i] = scan.nextInt(); //user input if(array[i]<-999 || array[i]>999){ //check if value is inside the range System.out.println("Please enter a number between -999 to 999"); i--; } } //...
Can someone convert this to C++ Please! import java.util.*; // for Random import java.util.Scanner; // for...
Can someone convert this to C++ Please! import java.util.*; // for Random import java.util.Scanner; // for Scanner class game{    public static void main(String args[])    {        // generating a random number        Random rand = new Random();        int code = rand.nextInt(99999) + 1, chances = 1, help, turn, i,match, sum;               // for input        Scanner sc = new Scanner(System.in);               // running for 10 times   ...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT