70.2k views
3 votes
Consider you are asked to decode a secret message. The coded message is in numbers and each number stands for a

specific letter. You discover enough of the secret code to decode the current message. So far, you know:
• 1 represents “D”
• 2 represents “W”
• 3 represents “E”
• 4 represents “L”
• 5 represents “H”
• 6 represents “O”
• 7 represents “R”
Write a program that prompts the user for 10 numbers, one at a time, and prints out the decoded message. If the user
enters a number that is not one of those already deciphered, prompt him/her for a new number. Test your code with the
following input: 5 3 4 4 6 2 6 7 4 1

WRITE IN THE PROGRAMMING LANGUAGE: JAVA

User Oghli
by
7.2k points

1 Answer

2 votes

Here is an example of a program in Java that prompts the user for 10 numbers, one at a time, and prints out the decoded message based on the code you provided:

import java.util.Scanner;

public class DecodeMessage {

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

// Create a mapping of numbers to letters

char[] letters = {'D', 'W', 'E', 'L', 'H', 'O', 'R'};

int[] numbers = {1, 2, 3, 4, 5, 6, 7};

// Prompt the user for 10 numbers

StringBuilder decodedMessage = new StringBuilder();

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

System.out.print("Enter a number: ");

int input = scanner.nextInt();

// Check if the input is a valid number

boolean valid = false;

for (int j = 0; j < numbers.length; j++) {

if (input == numbers[j]) {

decodedMessage.append(letters[j]);

valid = true;

break;

}

}

// If the input is not a valid number, prompt the user again

if (!valid) {

System.out.println("Invalid number. Please enter a valid number.");

i--;

}

}

// Print the decoded message

System.out.println("Decoded message: " + decodedMessage.toString());

}

}

This program uses a Scanner to prompt the user for input, a StringBuilder to construct the decoded message, and two arrays letters and numbers to store the mapping of letters and numbers. The program uses a for loop to prompt the user for 10 numbers, and inside the loop, it checks if the input is a valid number (by checking if it exists in the numbers array) and, if it is, it appends the corresponding letter to the decoded message. If the input is not a valid number, the program prints an error message and the loop iterates again, prompting the user for a new number. Finally, it prints the decoded message.

The test input you provided will output "HELHOR"

User Franz Becker
by
7.6k points