Skip to main content

"Encode” integers from an array via a given scheme to characters



Since I'm rather new to Java, I am not familiar with all the ways of handling this type of an assignment. I studied C and C# throughout my high school but I just started Java few days ago.





The task goes like this:





Write a program that reads 10 single-digit integers and displays a string consisting of 10 characters using the coding scheme: Digit Corresponding Character 0-a 1-b 2-c … … 9-j For example, if input consists of the 10 digits 1 8 6 1 0 3 1 8 5 5, the application responds with "bigbadbiff."





Since I moved from C and C# at first I had trouble allowing user to input the integers of the array, but I got that figured out. And this is what I got so far.







import java.util.*;



public class UnsualCoding

{

public static void main (String[] args)

{

Scanner util = new Scanner(System.in);

int[] x = new int[5];

int counter = 0;



for(int i = 0; i < x.length && util.hasNextInt(); i++)

{

x[i] = util.nextInt();

counter++;

}



System.out.println("\n\n");

System.out.println("Our array looks like");



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

{

System.out.println(x[i]);

}



System.out.println("\n\n");



}



}







Should I create a list, copy the content from an array to it and do the change or should I approach this problem differently? Can I convert the array to string? Also how can I bind/assign the characters to the given numbers?





Thank you.


Comments

  1. Since there are only 10 possibilities, you could put the characters that you want to encode into an array, and use the int inputs as the index to that array.

    char[] y = new char[]{'a','b','c','d','e','f','g','h','i','j'};


    Then the only part of your code that would change would be where you print it out :

    System.out.println(y[x[i]]);


    Though you may want to change your x array to be of arbitrary length as well.

    ReplyDelete
  2. You can do it like this:

    Scanner input = new Scanner(System.in);
    int count = 10;
    StringBuilder result = new StringBuilder(count);
    for(int i = 0; i < count; i++) result.append((char)(input.nextInt() + 'a'));
    System.out.println(result);


    INPUT:

    1 8 6 1 0 3 1 8 5 5


    OUTPUT:

    bigbadbiff

    ReplyDelete
  3. You can Map each numeric value to a letter. Then you pull from the Map for each number found in the input string. You will need a String to keep track of all the retrieved characters. After that you can return the String that was created.

    ReplyDelete
  4. First of all - you need some kind of mapping between digits and characters representing them. When you need mapping best to have is a Map!

    Map <Integer, Character> digitToCharacter = new HashMap<Integer, Character>();
    char baseCharacter = 'a';
    for (int i = 0; i< 10 ; i++) {
    digitToCharacter.put(i, baseCharacter++);
    }

    System.out.println("--" + digitToCharacter.get(1));


    during your printing of content:

    for(int i = 0; i < x.length; i++)
    {
    System.out.println(x[i]);
    }


    you would simply need to get value from map:

    for(int i = 0; i < x.length; i++)
    {
    System.out.println( digitToCharacter.get(i)));
    }


    but because you need a String, you don't have to write values to output - you need to append them to single string.

    String result = null;
    for(int i = 0; i < x.length; i++)
    {
    result += digitToCharacter.get(i)); // that isn't performace optimal, but it's enough and good for begginer
    }

    ReplyDelete
  5. Should I create a list, copy the content from an array to it and do the change or should I approach this problem differently?


    You could use a list to accumulate the result, or you could print the result as you accumulate it (you can use System.out.print(ch) to print an individual character).


    Also how can I bind/assign the characters to the given numbers?


    You could declare:

    char[] symbols = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'};


    Then, symbols[d] is the symbol for digit d.

    Or you might use that in unicode, lowercase letters occupy a contiguous range of character codes in alphabetical order, and use arithmetic to compute the codepoint of the next character: char symbol = (char) ('a' + digit);

    ReplyDelete

Post a Comment

Popular posts from this blog

Why is this Javascript much *slower* than its jQuery equivalent?

I have a HTML list of about 500 items and a "filter" box above it. I started by using jQuery to filter the list when I typed a letter (timing code added later): $('#filter').keyup( function() { var jqStart = (new Date).getTime(); var search = $(this).val().toLowerCase(); var $list = $('ul.ablist > li'); $list.each( function() { if ( $(this).text().toLowerCase().indexOf(search) === -1 ) $(this).hide(); else $(this).show(); } ); console.log('Time: ' + ((new Date).getTime() - jqStart)); } ); However, there was a couple of seconds delay after typing each letter (particularly the first letter). So I thought it may be slightly quicker if I used plain Javascript (I read recently that jQuery's each function is particularly slow). Here's my JS equivalent: document.getElementById('filter').addEventListener( 'keyup', function () { var jsStart = (new Date).getTime()...

Is it possible to have IF statement in an Echo statement in PHP

Thanks in advance. I did look at the other questions/answers that were similar and didn't find exactly what I was looking for. I'm trying to do this, am I on the right path? echo " <div id='tabs-".$match."'> <textarea id='".$match."' name='".$match."'>". if ($COLUMN_NAME === $match) { echo $FIELD_WITH_COLUMN_NAME; } else { } ."</textarea> <script type='text/javascript'> CKEDITOR.replace( '".$match."' ); </script> </div>"; I am getting the following error message in the browser: Parse error: syntax error, unexpected T_IF Please let me know if this is the right way to go about nesting an IF statement inside an echo. Thank you.