Difference between revisions of "Cellphone Texting"

From CompSciWiki
Jump to: navigation, search
(Added quotations to student quotes)
 
(10 intermediate revisions by one other user not shown)
Line 3: Line 3:
 
|ProblemName=Cellphone Texting
 
|ProblemName=Cellphone Texting
  
|Problem=In non-smart cell phones, text input can be handled by a
+
|Problem=(FROM COMSCI CONTEST 2010)<BR>In non-smart cell phones, text input can be handled by a
 
technique called multi-tap(example picture: [http://www.keypadletters.com/ link here]). With multi-tap, you use the
 
technique called multi-tap(example picture: [http://www.keypadletters.com/ link here]). With multi-tap, you use the
 
letters on each key, and press a key multiple times to
 
letters on each key, and press a key multiple times to
Line 15: Line 15:
 
phone, force the keys 7 and 9 to have four characters each. All other keys have 3
 
phone, force the keys 7 and 9 to have four characters each. All other keys have 3
 
characters.
 
characters.
 
+
<br>
 
Write a program which, given a word (a string of upper case letters with no
 
Write a program which, given a word (a string of upper case letters with no
 
spaces), outputs the sequence of keystrokes using multi-tap. If a key is pressed
 
spaces), outputs the sequence of keystrokes using multi-tap. If a key is pressed
 
multiple times, it should appear that many times in the input. A pause is indicated
 
multiple times, it should appear that many times in the input. A pause is indicated
 
by a single space.
 
by a single space.
 
+
<br>
 
Examples:
 
Examples:
 
{{OutputBlock
 
{{OutputBlock
 
|Code=
 
|Code=
Enter code: 222666 62227777444
+
Enter code: 222666 67777222444
Translated Code: COMCSI
+
Translated Code: COMSCI
 
Enter code: 7 2 777 2 7777 444 8 444 222
 
Enter code: 7 2 777 2 7777 444 8 444 222
 
Translated Code: PARASITIC
 
Translated Code: PARASITIC
Line 33: Line 33:
 
This problem will cover the following topics:
 
This problem will cover the following topics:
 
*[[Control_Structures|If and nested if statements]]
 
*[[Control_Structures|If and nested if statements]]
*[[Named_Constants|Named constants]]
+
*[[Processing_Arrays_(using for loops)|Arrays]]
 
*[[Input using Scanner|Scanner]]
 
*[[Input using Scanner|Scanner]]
 
*[[Output_using_System.out.|System.out]]
 
*[[Output_using_System.out.|System.out]]
<br>
+
*[[Arithmetic_Operators|Modulus]]
Example: User inputs "2" for the month and "2004" for the year would result in something like "February 2004 has 29 days."
+
*[[While Loops| While loops]]
<br>
+
<br>
+
  
|SideSectionTitle=By Students...
 
  
|SideSection=I remember coming into COMP 1010 having taken AP Computer Science in high school. One thing to note is the KISS theory, Keep it Simple Stupid. In other words, don't over complicate the matter where even yourself can't understand your own code looking over it. <br><br>Back in my day it was a bit of a game to try and code the fewest lines as possible, I think now it is more about code readability and code cleanliness, the flow of logic. Does it make sense? Is it readable? Can someone easily follow the thought process? <br><br>You also don't realize how important and how much you will appreciate comments until you have to debug code that has not been commented or that you haven't touched in a while. I used to be lazy to comment one day I was at work and I had to fix a bug in a program that I wrote. It was quite the adventure trying to remember what I was thinking back when I wrote it to which I am now appreciative of comments that people write including my own. Computers are fast these days; one core, two core, three core, and more, and number of lines is a story of the past.
+
|SideSectionTitle=...By Students
  
 +
|SideSection="COMP 1010 is where I first learned how to make a program. I was only taking that course for prerequisite and do not have interest on it, but as time goes by, I notice that I was enjoying myself making a program.
 +
 +
I learned that commenting important parts of the code really helps a lot especially to myself since I can track down why I did that code. Also, if you want to check or want to debug your code, try commenting out the parts you don't need yet and try to output some parts of the code to see what your code is doing. And the last but not the least. Don't do all the coding in one shot, it will take you more time to debug it than running the program while the coding is still small."
 
<BR>
 
<BR>
  
Line 57: Line 57:
  
  
Define your named constants and provide them with appropriate values, in this example there is one constant for 31 days one for 30 days and one for February. You can name them however you want but be sure to declare them as static constants since we are working in static main. Also note that it is declared outside of main, more often named constants are used throughout the java class where multiple functions can access it.
+
Next is to think all the step necessary for the program to work.<br>
{{CodeBlock
+
*Get user input
|Code=
+
*Check if the input are all numbers or numbers with spaces
final static int MONTH30 = 30;
+
*Process the input and change them to letters
final static int FEB = 28;
+
{{note}}This solution will show 3 method to do all these steps to make the program look neat. You can always put all codes in main but it will be messy<br>
final static int MONTH31 = 31;
+
}}
+
  
  
Next define your local variables and initialize them to sentinel values for future error checking described later. We will need a year, monthNum and monthName as defined accordingly.
+
First to get the Input of the user.<br>
 +
In order to get the user input, you have to use the Scanner's method .nextLine() in order to get the whole input. Since you do not know the when user will stop, you have to put the scanner inside a while loop. You also want to check validation of the input but let another method handle the validation. If input is not valid, output an error message to alert the user.
 +
 
 
{{CodeBlock
 
{{CodeBlock
 
|Code=
 
|Code=
int year, monthNum;
+
Scanner scan = new Scanner(System.in); // To enter the input
String monthName;
+
String input = " ";                     // Store the input
Scanner input = new Scanner(System.in);
+
String convert = "";                 // Store the translated input
+
System.out.print("Enter code: ");
//sentinel values for error checking
+
monthNum = -1;
+
year = -1;
+
monthName = "";
+
}}
+
  
 
+
while(!input.equals(""))
Capturing the user input using Scanner and to make sure the user did not enter non-numeric value
+
 
+
{{CodeBlock
+
|Code=
+
System.out.print("Please enter the month [Jan(1) to Dec(12)]: ");
+
if(input.hasNextInt())
+
 
{
 
{
monthNum = input.nextInt();
+
input = scan.nextLine();         // scan will get the user input and store in in the String input
  
System.out.print("Please enter the Year: ");
+
if(checkInput(input))           // calls the method checkInput to check for validation
if(input.hasNextInt())
+
 
{
 
{
 
+
convert = codeEncription(input);                 //calls the method codeEcription to translate the input into letters
                 //code here
+
System.out.print("Translated Code: "+convert);  //output message
 
+
System.out.print("\nEnter code: ");
}
+
}
 
else
 
else
 
{
 
{
System.out.println("Please try again, there was an error with the month or the year you have entered");
+
System.out.println("Invalid Input");              //error message
 +
System.out.print("Enter code: ");
 
}
 
}
}
+
 
else
+
{
+
System.out.println("Invalid month number entered, choose between 1 - 12 (Jan - Dec)");
+
 
}
 
}
 
}}
 
}}
 
{{OutputBlock
 
{{OutputBlock
 
|Code=
 
|Code=
Please enter the month [Jan(1) to Dec(12)]: abcd
+
Enter code: 23a43
Please enter the Year: 2009
+
Invalid Input
Invalid input of month
+
Enter code: 77 88 444 9999 9999 444 222 2 555
}}
+
Translated Code: QUIZZICAL
{{OutputBlock
+
|Code=
+
Please enter the month [Jan(1) to Dec(12)]: 12
+
Please enter the Year: asdf
+
Invalid Input of Year
+
 
}}
 
}}
  
  
Now we have to break up the problem into a series of cases and separate the conditions into if statements. The first 3 if statements is for error checking and validate the user input to make sure valid numbers were entered for month and year. <br>
+
Next is to make a method that will validate the user input.It will have a String as a parameter to pass the input to this method<br>
 
+
You have to check each character in the input to see if there is an invalid input. While loops is still necessary for this task since you don't know if you will find an error or not in the input. This method will return true if its valid or false if invalid.
First case, if user left both month and year blank.
+
 
{{CodeBlock
 
{{CodeBlock
 
|Code=
 
|Code=
if (monthNum <= 0 && year <= 999)
+
public static boolean checkInput(String input)
System.out.println("Please try again, there was an error with the month and the year you have entered");
+
{
}}
+
boolean check = true;
{{OutputBlock
+
int counter = 0;
|Code=
+
Please enter the month [Jan(1) to Dec(12)]: -1
+
Please enter the Year: 987
+
Please try again, there was an error with the month and the year you have entered
+
}}
+
  
 +
while( check && counter < input.length()) 
 +
{
 +
if(input.charAt(counter) == ' ')        //if space is found in the input its still valid
 +
counter++;
 +
else if(input.charAt(counter) < '0' {{!}}{{!}} input.charAt(counter) > '9')  //check if its a number or not
 +
check = false;
 +
else
 +
counter++;
 +
}
  
Second case, if user entered an invalid monthNumber like a negative month number
+
return check;     //returns true if valid or false if not valid
{{CodeBlock
+
|Code=
+
else if (monthNum <= 0)
+
{
+
System.out.println("Please try again, there was an error with the month you have entered");
+
 
}
 
}
}}
 
{{OutputBlock
 
|Code=
 
Please enter the month [Jan(1) to Dec(12)]: -1
 
Please enter the Year: 2009
 
Please try again, there was an error with the month you have entered
 
 
}}
 
}}
  
  
Third case, if user entered an invalid year, i.e. negative or in this problem we assume year 1000 is the first year
+
Next step is to make a method that will translate the input.It has String as a parameter as well.<br>
 +
In order to translate the input, you have to check each character in the String. This means you can use for loops in this method since you will know went exactly to stop. Every time you check a character, store the current character and count how many are there after the current character change. Then pass the current character and the number of count you had to another method what will change the number into Letters
 
{{CodeBlock
 
{{CodeBlock
 
|Code=
 
|Code=
else if (year <= 999)
+
public static String codeEncription(String input)
 
{
 
{
System.out.println("Please try again, there was an error with the month you have entered");
+
String output = "";            //Store each number that is translated into letter
}
+
int counter = 1;                //count the number of same consecutive number
}}
+
char last = input.charAt(0);    //Initialize the last to the first character of the string
{{OutputBlock
+
char cur = input.charAt(0);    //Initialize the cur to the first character of the string
|Code=
+
for(int i = 1 ; i <= input.length();i++)
Please enter the month [Jan(1) to Dec(12)]: 12
+
{
Please enter the Year: 987
+
if(i < input.length())           
Please try again, there was an error with the month you have entered
+
{
}}
+
cur = input.charAt(i);    //store the current character to cur
 +
}
 +
else
 +
{
 +
cur = '.';                  //this else statement is necessary to complete the last letter of the input
 +
}
  
 +
if(cur == last)
 +
{
 +
counter++;                  //number of same consecutive number
 +
}
 +
else
 +
{
  
 
+
output += converter(last,counter) +"";  //this will call converter() method that will change the number into letter
The last case, which is most important since it is processing the valid input will be the next step. In this case there is a set of nested cases. Again, we will have to separate the conditions into statements. In this problem we separated the months by 31 days, 30 days, and February as a case of its own for calculating leap years.<br>
+
last = cur;                            //to set the last into the current character
 
+
counter = 1;
Months with 31 days, since we are assuming Jan = 0, the condition will "or" all integer representations of the months with 31 days. Remember July and August are back to back months with 31 days! The first condition checks for the appropriate monthNum and the nested conditions will assign the appropriate monthName depending on which integer was chosen. There may be alternate solutions and methods to solve this problem but for the sake of example and topics to cover we have chosen this method. Lastly, System.out.println prints an meaningful output message.
+
}
{{CodeBlock
+
}
|Code=
+
return output;                                           // return the translated code
//JAN //MAR //MAY //JUL //AUG //OCT //DEC
+
if (monthNum == 1 {{!}}{{!}} monthNum == 3 {{!}}{{!}} monthNum == 5 {{!}}{{!}}
+
monthNum == 7 {{!}}{{!}} monthNum == 8 {{!}}{{!}} monthNum == 10 {{!}}{{!}}
+
monthNum == 12)
+
{
+
if (monthNum == 1)
+
monthName = "January";
+
else if (monthNum == 3)
+
monthName = "March";
+
else if (monthNum == 5)
+
monthName = "May";
+
else if (monthNum == 7)
+
monthName = "July";
+
else if (monthNum == 8)
+
monthName = "August";
+
else if (monthNum == 10)
+
monthName = "October";
+
else if (monthNum == 12)
+
monthName = "December";
+
+
System.out.println(monthName + " " + year + " has " + MONTH31 + " days.");
+
 
}
 
}
}}
 
 
{{OutputBlock
 
|Code=
 
Please enter the month [Jan(1) to Dec(12)]: 3
 
Please enter the Year: 2009
 
March 2009 has 31 days.
 
 
}}
 
}}
  
  
The case of February checks if monthNum = 1 but for the nested conditions, it checks if the year is divisible by 4 by using the mod operator. If it is in fact a leap year, 1 is added to the constant.
+
Last step is to make a method that will convert the number into letter using String array and Modulus.<br>
 +
In this method, there are two parameter ,char and int, the char represent the number and the in represent how many consecutive number was found in the current search from the other method. This will return the equivalent letter or if its space it will return empty String.  
 
{{CodeBlock
 
{{CodeBlock
 
|Code=
 
|Code=
//FEB
+
public static String converter(char find,int count)
else if (monthNum == 2)
+
 
{
 
{
monthName = "February";
+
        //String array are manually entered. The arrangement of letters is necessary in order to get the right letter
 +
String[] two = {"C","A","B"};
 +
String[] three = {"F","E","D"};
 +
String[] four = {"I","G","H"};
 +
String[] five = {"L","J","K"};
 +
String[] six = {"O","M","N"};
 +
String[] seven = {"S","P","Q","R"};
 +
String[] eight = {"V","T","U"};
 +
String[] nine = {"Z","W","X","Y"};
 +
String convert = "";
  
//check for leap
+
        //doing a modulus will return either 1,2 or 0 if its mod 3 and 1,2,3 or 0 if its mod 4
if (year % 4 == 0)
+
if(find == '2'){
System.out.println(monthName + " " + year + " has " + (FEB + 1) + " days.");
+
convert = two[(count%3)];
else
+
}else if(find == '3')
System.out.println(monthName + " " + year + " has " + FEB + " days.");
+
{
}
+
convert = three[(count%3)];
}}
+
}else if(find == '4')
{{OutputBlock
+
{
|Code=
+
convert = four[(count%3)];
Please enter the month [Jan(1) to Dec(12)]: 2
+
}else if(find == '5')
Please enter the Year: 2008
+
{
February 2009 has 29 days.
+
convert = five[(count%3)];
}}
+
}else if(find == '6')
{{OutputBlock
+
{
|Code=
+
convert = six[(count%3)];
Please enter the month [Jan(1) to Dec(12)]: 2
+
}else if(find == '7')
Please enter the Year: 2009
+
{
February 2009 has 28 days.
+
convert = seven[(count%4)];
}}
+
}else if(find == '8')
 +
{
 +
convert = eight[(count%3)];
 +
}else if(find == '9')
 +
{
 +
convert = nine[(count%4)];
 +
}
  
 
+
return convert;
Months with 30 days are the last group of valid inputs to check. Similar to the months with 31 days, the first condition checks for an appropriate monthNum and the nested condition assigns the appropriate monthName.
+
{{CodeBlock
+
|Code=
+
//APR //JUN //SEP //NOV
+
else if (monthNum == 4{{!}}{{!}} monthNum == 6 {{!}}{{!}} monthNum == 9 {{!}}{{!}} monthNum == 11)
+
{
+
if (monthNum == 4)
+
monthName = "April";
+
else if (monthNum == 6)
+
monthName = "June";
+
else if (monthNum == 9)
+
monthName = "September";
+
else if (monthNum == 11)
+
monthName = "November";
+
+
System.out.println(monthName + " " + year + " has " + MONTH30 + " days.");
+
 
}
 
}
}}
 
{{OutputBlock
 
|Code=
 
Please enter the month [Jan(1) to Dec(12)]: 11
 
Please enter the Year: 2009
 
November 2009 has 30 days.
 
 
}}
 
}}
  
  
 
+
This program will helps you how to make a clean code and make sure you make it simple as possible.
Lastly, for additional robustness, you can check if the user enters a monthNum that is too high. Remember, initially we checked for negative monthNum, but this time is now the opposite end of the spectrum where the monthNum is too beyond the scope. If the monthNum is too high output a meaningful error message.
+
{{CodeBlock
+
|Code=
+
//number is larger than 11
+
else
+
System.out.println("Invalid month number entered, choose between 1 - 12 (Jan - Dec)");
+
}}
+
{{OutputBlock
+
|Code=
+
Please enter the month [Jan(1) to Dec(12)]: 13
+
Please enter the Year: 2009
+
Invalid month number entered, choose between 1 - 12 (Jan - Dec)
+
}}
+
 
+
 
+
This concludes the program, compile and run.
+
 
   
 
   
 
|SolutionCode=
 
|SolutionCode=
 +
import java.util.Scanner;
 
import javax.swing.*;
 
import javax.swing.*;
import java.util.Scanner;
 
  
public class DaysInAMonth
+
public class CellText
 
{
 
{
final static int MONTH30 = 30;
+
    public static void main(String[] args)
final static int FEB = 28;
+
    {
final static int MONTH31 = 31;
+
        Scanner scan = new Scanner(System.in); // To enter the input
 +
String input = " ";                     // Store the input
 +
String convert = "";                 // Store the translated input
 +
System.out.print("Enter code: ");
  
public static void main(String[] args)
+
while(!input.equals(""))
{
+
int year, monthNum;
+
String monthName;
+
Scanner input = new Scanner(System.in);
+
 
+
//sentinel values for error checking
+
monthNum = -1;
+
year = -1;
+
monthName = "";
+
 
+
System.out.print("Please enter the month [Jan(1) to Dec(12)]: ");
+
if(input.hasNextInt())
+
 
{
 
{
monthNum = input.nextInt();
+
input = scan.nextLine();         // scan will get the user input and store in in the String input
  
System.out.print("Please enter the Year: ");
+
if(checkInput(input))           // calls the method checkInput to check for validation
if(input.hasNextInt())
+
 
{
 
{
year = input.nextInt();
+
convert = codeEncription(input);                 //calls the method codeEcription to translate the input into letters
 
+
System.out.print("Translated Code: "+convert);   //output message
if (monthNum <= 0 && year <= 999)
+
System.out.print("\nEnter code: ");
System.out.println("Please try again, there was an error with the month and the year you have entered");
+
else if (monthNum <= -1)
+
{
+
System.out.println("Please try again, there was an error with the month you have entered");
+
 
}
 
}
else if (year <= 999)
+
else
{
+
{
System.out.println("Please try again, there was an error with the month you have entered");
+
System.out.println("Invalid Input");             //error message
}
+
System.out.print("Enter code: ");
else
+
}
//JAN //MAR //MAY //JUL //AUG //OCT //DEC
+
if (monthNum == 1 {{!}}{{!}} monthNum == 3 {{!}}{{!}} monthNum == 5 {{!}}{{!}} monthNum == 7 {{!}}{{!}} monthNum == 8 {{!}}{{!}} monthNum == 10 {{!}}{{!}} monthNum == 12)
+
{
+
if (monthNum == 1)
+
monthName = "January";
+
else if (monthNum == 3)
+
monthName = "March";
+
else if (monthNum == 5)
+
monthName = "May";
+
else if (monthNum == 7)
+
monthName = "July";
+
else if (monthNum == 8)
+
monthName = "August";
+
else if (monthNum == 10)
+
monthName = "October";
+
else if (monthNum == 12)
+
monthName = "December";
+
  
System.out.println(monthName + " " + year + " has " + MONTH31 + " days.");
+
}
}
+
//FEB
+
else if (monthNum == 2)
+
{
+
monthName = "February";
+
  
//check for leap
 
if (year % 4 == 0)
 
System.out.println(monthName + " " + year + " has " + (FEB + 1) + " days.");
 
else
 
System.out.println(monthName + " " + year + " has " + FEB + " days.");
 
}
 
//APR //JUN //SEP //NOV
 
else if (monthNum == 4{{!}}{{!}} monthNum == 6 {{!}}{{!}} monthNum == 9 {{!}}{{!}} monthNum == 11)
 
{
 
if (monthNum == 4)
 
monthName = "April";
 
else if (monthNum == 6)
 
monthName = "June";
 
else if (monthNum == 9)
 
monthName = "September";
 
else if (monthNum == 11)
 
monthName = "November";
 
  
System.out.println(monthName + " " + year + " has " + MONTH30 + " days.");
+
    }
}
+
 
//number is larger than 11
+
public static boolean checkInput(String input)
else
+
{
System.out.println("Invalid month number entered, choose between 1 - 12 (Jan - Dec)");
+
boolean check = true;
 +
int counter = 0;
 +
 
 +
while( check && counter < input.length()) 
 +
{
 +
if(input.charAt(counter) == ' ')        //if space is found in the input its still valid
 +
counter++;
 +
else if(input.charAt(counter) < '0' {{!}}{{!}} input.charAt(counter) > '9')  //check if its a number or not
 +
check = false;
 +
else
 +
counter++;
 +
}
 +
 
 +
return check;    //returns true if valid or false if not valid
 +
}
 +
 
 +
public static String codeEncription(String input)
 +
{
 +
String output = "";            //Store each number that is translated into letter
 +
int counter = 1;                //count the number of same consecutive number
 +
char last = input.charAt(0);    //Initialize the last to the first character of the string
 +
char cur = input.charAt(0);    //Initialize the cur to the first character of the string
 +
for(int i = 1 ; i <= input.length();i++)
 +
{
 +
if(i < input.length())           
 +
{
 +
cur = input.charAt(i);     //store the current character to cur
 
}
 
}
 
else
 
else
 
{
 
{
System.out.println("Invalid Input");
+
cur = '.';                  //this else statement is necessary to complete the last letter of the input
 +
}
 +
 
 +
if(cur == last)
 +
{
 +
counter++;                  //number of same consecutive number
 +
}
 +
else
 +
{
 +
 
 +
output += converter(last,counter) +"";  //this will call converter() method that will change the number into letter
 +
last = cur;                            //to set the last into the current character
 +
counter = 1;
 
}
 
}
 
}
 
}
else
+
return output;                                          // return the translated code
 +
}
 +
 
 +
 
 +
public static String converter(char find,int count)
 +
{
 +
//String array are manually entered. The arrangement of letters is necessary in order to get the right letter
 +
String[] two = {"C","A","B"};
 +
String[] three = {"F","E","D"};
 +
String[] four = {"I","G","H"};
 +
String[] five = {"L","J","K"};
 +
String[] six = {"O","M","N"};
 +
String[] seven = {"S","P","Q","R"};
 +
String[] eight = {"V","T","U"};
 +
String[] nine = {"Z","W","X","Y"};
 +
String convert = "";
 +
 
 +
//doing a modulus will return either 1,2 or 0 if its mod 3 and 1,2,3 or 0 if its mod 4
 +
if(find == '2'){
 +
convert = two[(count%3)];
 +
}else if(find == '3')
 
{
 
{
System.out.println("Invalid Input");
+
convert = three[(count%3)];
 +
}else if(find == '4')
 +
{
 +
convert = four[(count%3)];
 +
}else if(find == '5')
 +
{
 +
convert = five[(count%3)];
 +
}else if(find == '6')
 +
{
 +
convert = six[(count%3)];
 +
}else if(find == '7')
 +
{
 +
convert = seven[(count%4)];
 +
}else if(find == '8')
 +
{
 +
convert = eight[(count%3)];
 +
}else if(find == '9')
 +
{
 +
convert = nine[(count%4)];
 
}
 
}
 +
 +
return convert;
 
}
 
}
 
}
 
}
 
}}
 
}}

Latest revision as of 15:33, 8 December 2011

Back to the Program-A-Day homepage

Problem

(FROM COMSCI CONTEST 2010)
In non-smart cell phones, text input can be handled by a technique called multi-tap(example picture: link here). With multi-tap, you use the letters on each key, and press a key multiple times to access different letters. For instance, to get the letter 'a', you press the 2 key once, but to get 'n', you press the 6 key twice (the first press gives you 'm', the second switches 'm' to 'n'). A slight pause by the user will indicate the end of inputting one character and a beginning of the input of the next character. The letters 'q' and 'z', not originally part of the letters on a phone, force the keys 7 and 9 to have four characters each. All other keys have 3 characters.
Write a program which, given a word (a string of upper case letters with no spaces), outputs the sequence of keystrokes using multi-tap. If a key is pressed multiple times, it should appear that many times in the input. A pause is indicated by a single space.
Examples:

 Enter code: 222666 67777222444
Translated Code: COMSCI
Enter code: 7 2 777 2 7777 444 8 444 222
Translated Code: PARASITIC 


This problem will cover the following topics:

 

...By Students

"COMP 1010 is where I first learned how to make a program. I was only taking that course for prerequisite and do not have interest on it, but as time goes by, I notice that I was enjoying myself making a program.

I learned that commenting important parts of the code really helps a lot especially to myself since I can track down why I did that code. Also, if you want to check or want to debug your code, try commenting out the parts you don't need yet and try to output some parts of the code to see what your code is doing. And the last but not the least. Don't do all the coding in one shot, it will take you more time to debug it than running the program while the coding is still small."

Solution

Start by importing the swing java package.

 import javax.swing.*;
import java.util.Scanner; 


Next is to think all the step necessary for the program to work.

  • Get user input
  • Check if the input are all numbers or numbers with spaces
  • Process the input and change them to letters

Note Note: This solution will show 3 method to do all these steps to make the program look neat. You can always put all codes in main but it will be messy


First to get the Input of the user.
In order to get the user input, you have to use the Scanner's method .nextLine() in order to get the whole input. Since you do not know the when user will stop, you have to put the scanner inside a while loop. You also want to check validation of the input but let another method handle the validation. If input is not valid, output an error message to alert the user.

 Scanner scan = new Scanner(System.in);  // To enter the input
String input = " ";                     // Store the input
String convert = "";	                // Store the translated input
System.out.print("Enter code: ");

while(!input.equals(""))
{
	input = scan.nextLine();         // scan will get the user input and store in in the String input

	if(checkInput(input))            // calls the method checkInput to check for validation
	{
		convert = codeEncription(input);                 //calls the method codeEcription to translate the input into letters
		System.out.print("Translated Code: "+convert);   //output message
		System.out.print("\nEnter code: ");
		}
	else
	{
		System.out.println("Invalid Input");              //error message
		System.out.print("Enter code: ");
	}

} 
 Enter code: 23a43
Invalid Input
Enter code: 77 88 444 9999 9999 444 222 2 555
Translated Code: QUIZZICAL 


Next is to make a method that will validate the user input.It will have a String as a parameter to pass the input to this method
You have to check each character in the input to see if there is an invalid input. While loops is still necessary for this task since you don't know if you will find an error or not in the input. This method will return true if its valid or false if invalid.

 public static boolean checkInput(String input)
{
	boolean check = true;
	int counter = 0;

	while( check && counter < input.length())  
	{
		if(input.charAt(counter) == ' ')        //if space is found in the input its still valid
			counter++;
		else if(input.charAt(counter) < '0' || input.charAt(counter) > '9')  //check if its a number or not
			check = false;
		else
			counter++;
	}

	return check;     //returns true if valid or false if not valid
} 


Next step is to make a method that will translate the input.It has String as a parameter as well.
In order to translate the input, you have to check each character in the String. This means you can use for loops in this method since you will know went exactly to stop. Every time you check a character, store the current character and count how many are there after the current character change. Then pass the current character and the number of count you had to another method what will change the number into Letters

 public static String codeEncription(String input)
{
	String output = "";             //Store each number that is translated into letter
	int counter = 1;                //count the number of same consecutive number
	char last = input.charAt(0);    //Initialize the last to the first character of the string
	char cur = input.charAt(0);     //Initialize the cur to the first character of the string
	for(int i = 1 ; i <= input.length();i++)
	{
		if(i < input.length())             
		{
			cur = input.charAt(i);     //store the current character to cur
		}
		else
		{
			cur = '.';                  //this else statement is necessary to complete the last letter of the input
		}

		if(cur == last)
		{
			counter++;                   //number of same consecutive number
		}
		else
		{

			output += converter(last,counter) +"";  //this will call converter() method that will change the number into letter
			last = cur;                             //to set the last into the current character
			counter = 1;
		}
	}
	return output;                                           // return the translated code
} 


Last step is to make a method that will convert the number into letter using String array and Modulus.
In this method, there are two parameter ,char and int, the char represent the number and the in represent how many consecutive number was found in the current search from the other method. This will return the equivalent letter or if its space it will return empty String.

 public static String converter(char find,int count)
{
        //String array are manually entered. The arrangement of letters is necessary in order to get the right letter
	String[] two = {"C","A","B"};
	String[] three = {"F","E","D"};
	String[] four = {"I","G","H"};
	String[] five = {"L","J","K"};
	String[] six = {"O","M","N"};
	String[] seven = {"S","P","Q","R"};
	String[] eight = {"V","T","U"};
	String[] nine = {"Z","W","X","Y"};
	String convert = "";

        //doing a modulus will return either 1,2 or 0 if its mod 3 and 1,2,3 or 0 if its mod 4
	if(find == '2'){
		convert = two[(count%3)];
	}else if(find == '3')
	{
		convert = three[(count%3)];
	}else if(find == '4')
	{
		convert = four[(count%3)];
	}else if(find == '5')
	{
		convert = five[(count%3)];
	}else if(find == '6')
	{
		convert = six[(count%3)];
	}else if(find == '7')
	{
		convert = seven[(count%4)];
	}else if(find == '8')
	{
		convert = eight[(count%3)];
	}else if(find == '9')
	{
		convert = nine[(count%4)];
	}

	return convert;
} 


This program will helps you how to make a clean code and make sure you make it simple as possible.

Code

Solution Code

Back to the Program-A-Day homepage