I am learning Java in programming right now. I need to write a program that should have an output like this:
The program says "Type ten names". Then ten names sould be typed a person. Then the program chooses a random name from the list and displays it on screen. What should be the Java code for this task? Thank you.
Scanner scan = new Scanner(System.in);
//take 10 string values from user
System.out.println("Enter 10 names: ");
String n = scan.nextLine();
String [] names = new String{n};
//store the names in an array
for (int i = 0; i < 10; i++){
names[i] = scan.nextLine();
}
//sequentially print the names and upperCase them
for (String i : names){
System.out.println(i.toUpperCase());
}
scan.close();
}
To write a Java program that prompts the user to type ten names, and then randomly chooses and displays one of the names, you can follow these steps:
1. Import the necessary Java utility classes:
```java
import java.util.Scanner;
import java.util.Random;
```
2. Create a Scanner object to read user input:
```java
Scanner scanner = new Scanner(System.in);
```
3. Prompt the user to type ten names:
```java
System.out.println("Type ten names:");
```
4. Create an array to store the names:
```java
String[] names = new String[10];
```
5. Use a for loop to read the names from the user and store them in the array:
```java
for (int i = 0; i < 10; i++) {
names[i] = scanner.nextLine();
}
```
6. Use a Random object to generate a random index within the range of the array:
```java
Random random = new Random();
int randomIndex = random.nextInt(10);
```
7. Retrieve the randomly chosen name from the array using the random index:
```java
String randomName = names[randomIndex];
```
8. Display the randomly chosen name on the screen:
```java
System.out.println("Randomly chosen name: " + randomName);
```
Putting it all together, here's the complete Java code for your task:
```java
import java.util.Scanner;
import java.util.Random;
public class RandomNamePicker {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Type ten names:");
String[] names = new String[10];
for (int i = 0; i < 10; i++) {
names[i] = scanner.nextLine();
}
Random random = new Random();
int randomIndex = random.nextInt(10);
String randomName = names[randomIndex];
System.out.println("Randomly chosen name: " + randomName);
}
}
```
By running this code, you should be able to enter ten names and see a randomly chosen name displayed as output.