I want to make a program where you enter input in a for loop and after the iterations, a randomized string value from an array gets placed with it in the output message at the end. I do not want the string values to repeat, I want each value to only be produced once. How can I go about doing that? (the int values and the string values in the two arrays have to stay matched as well)
I want the output to be like:
Alex likes mangos and the number 3
John likes apples and the number 1
Jane likes bananas and the number 2
instead of:
Alex likes mangos and the number 3
John likes mangos and the number 3
Jane likes apples and the number 1
package example;
import javax.swing.JOptionPane;
import java.util.Random;
public class Example {
public static void main(String[] args) {
StringBuilder generator = new StringBuilder();
for (int a=1; a<4; a++){
String name = JOptionPane.showInputDialog(null, "Enter person " + a + "'s name");
Random random = new Random();
String [] fruit = {"apples", "bananas", "mangos"};
int [] number = {1, 2, 3};
int randomIndex = random.nextInt(fruit.length);
generator.append(name).append(" likes ").append(fruit[randomIndex]).append(" and the number ").append(number[randomIndex]).append("\n");
}
JOptionPane.showMessageDialog(null, generator);
}
}
Aucun commentaire:
Enregistrer un commentaire