(Java Programming)
Question 7:
Write a program that prompts the user to enter a 10 alphabets (A-Z) and converts it to numbers using the following mapping:
A, B, C = 8
D, E, F = 6
G, H, I = 4
J, K, L = 5
M, N, 0 = 7
P, Q, R, S = 2
T, U, V, W = 3
X, Y, Z = 1
Please be sure to use Object Oriented Programming concepts when designing and writing code for this question. Complete class(es) (if more than > 1 class is required) and main() method is required.
Expert Answer
Java Program:
import java.util.Scanner;
class Mapping
{
//Variable used for storing alphabets
private char[] alphabets;
//Argument Constructor
public Mapping(char[] alphas)
{
//Allocating size
alphabets = new char[10];
//Iterating over arrays
for(int i=0; i<10; i++)
{
//Copying alphabets
alphabets[i] = alphas[i];
}
}
//Method that translated character to number
public int getMap(char ch)
{
//Mapping character to number
if(ch == ‘A’ || ch == ‘B’ || ch == ‘C’) return 8;
else if(ch == ‘D’ || ch == ‘E’ || ch == ‘F’) return 6;
else if(ch == ‘G’ || ch == ‘H’ || ch == ‘I’) return 4;
else if(ch == ‘J’ || ch == ‘K’ || ch == ‘L’) return 5;
else if(ch == ‘M’ || ch == ‘N’ || ch == ‘0’) return 7;
else if(ch == ‘P’ || ch == ‘Q’ || ch == ‘R’ || ch == ‘S’) return 2;
else if(ch == ‘T’ || ch == ‘U’ || ch == ‘V’ || ch == ‘W’) return 3;
else if(ch == ‘X’ || ch == ‘Y’ || ch == ‘Z’) return 1;
else return 0;
}
//Converting to numbers and mapping values
public void convert()
{
System.out.print(“nn Converted to Numbers: “);
//Iterating over arrays
for(int i=0; i<10; i++)
{
//Copying alphabets
System.out.print(getMap(alphabets[i]));
}
System.out.println(“nn”);
}
}
//Driver class
class MappingDriver
{
//Main method
public static void main(String args[])
{
//Char array for holding user input
char[] ip = new char[10];
String ipStr;
//Scanner class object
Scanner sc = new Scanner(System.in);
//Reading input
System.out.print(“nn Input 10 alphabets: “);
ipStr = sc.nextLine();
//Converting to char array
ip = ipStr.toCharArray();
//Creating instance
Mapping obj = new Mapping(ip);
//Printing results
obj.convert();
}
}
_______________________________________________________________________________________________
Sample Output: