Write an application that uses an Array to store 10messages of type String. You
ID: 675558 • Letter: W
Question
Write an application that uses an Array to store 10messages of type String. You will store this Array with 10 messages of your choosing. For example, a message could be “I love Java the programming language!” or another message could be “I love Java the drink!” You may initialize your Array with the messages or have the user enter the messages. The choice is yours. Your Java code will contain a method called shoutOutCannedMessage() that will loop through the Array to iterate through your entire list and display each message and allow the user to select one. The shoutOutCannedMessage() will return the selected message String
Explanation / Answer
/**The java program MessageProgram that prompts
* to enter the user choice of an array of messages
* and then the method shoutOutCannedMessage returns
* the user selected choice to the main method*/
//MessageProgram.java
import java.util.Scanner;
public class MessageProgram
{
//create an array of messages
private static String messages[]=
{"I Love java",
"I love Java the programming language!",
"I love Java the drink!",
"Java is OOP",
"Java-James Gosling",
"Java virtual Machine",
"Fun to program-java",
"Platform independent-java",
"Open source-java",
"Have a smart programming-java"
};
public static void main(String[] args)
{
//call the method shoutOutCannedMessage
String selectedMessage=shoutOutCannedMessage();
//print the user selected choice
System.out.println("User selected choice is "+selectedMessage);
}
/**The method shoutOutCannedMessage that print the array of string
* messages and prompt for user choice and returns selected
* choice fromt the method.*/
private static String shoutOutCannedMessage()
{
//Create a scanner class
Scanner scanner=new Scanner(System.in);
//integer variable of choice
int choice;
//iterate over the messages array and print the values
for (int index = 0; index < messages.length; index++)
{
System.out.println((index+1)+")"+messages[index]);
}
System.out.println("Enter your choice .");
//prompt for user choice
choice=scanner.nextInt();
//return choice
return messages[choice-1];
}
}
----------------------------------------------------------------------------------------------------------------------------------------
Sample Output:
1)I Love java
2)I love Java the programming language!
3)I love Java the drink!
4)Java is OOP
5)Java-James Gosling
6)Java virtual Machine
7)Fun to program-java
8)Platform independent-java
9)Open source-java
10)Have a smart programming-java
Enter your choice .
6
User selected choice is Java virtual Machine
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.