How to show all content of an array in Java
this is my first post on this web site, so please be patience :) I'm studying java and I'm trying to create a small program that storage in two arrays the name of player and the attendance of them. I'm using JOptionPane for the 'user interface'. I would like, when the user ask for, to show the names and the respective attendance of them. Here it's my code(it's not completed):
import javax.swing.*;
import java.text.*;
public class Pelada{
public static void main(String []args){
String[] players = new String[10];
int[] attendance = new int[10];
int x = 0, z = 0, control = 0, posPlayer = 0;
String test;
while(control != 4){
control = Integer.parseInt(JOptionPane.showInputDialog(null,"1- Add new players \n 2- List \n 3- Increment attendance \n 4- Delete player \n 4- Exit", "Choose an option below", JOptionPane.I开发者_运维百科NFORMATION_MESSAGE));
if(control == 1){
players[x] = JOptionPane.showInputDialog(null, "New player: ", "Add New Player", JOptionPane.INFORMATION_MESSAGE);
attendance[x] = Integer.parseInt(JOptionPane.showInputDialog(null, "How many matchs have he played so far? ", "Attendance", JOptionPane.INFORMATION_MESSAGE));
x++;
}
else if(control == 2)
for (int i=0; i < players.length; i++){
JOptionPane.showMessageDialog(null, "Attendance = " + attendance[i], "N: " + i + "- " + players[i], JOptionPane.WARNING_MESSAGE);
}
else if(control == 3){
posPlayer = Integer.parseInt(JOptionPane.showInputDialog(null, "Choose the player id: ", "Player Id", JOptionPane.INFORMATION_MESSAGE));
attendance[posPlayer] = Integer.parseInt(JOptionPane.showInputDialog(null, "Increment ", "Attendance", JOptionPane.INFORMATION_MESSAGE));
}
}
}
}
Instead of having two arrays; one for players and one for attendance, make your code more object-oriented by creating a Player
class encapsulating the name and attendance of a player:
public class Player {
private final String name;
private final int attendance;
public Player(String name, int attendance) {
this.name = name;
this.attendance = attendance;
}
public String getName() {
return name;
}
public int getAttendance() {
return attendance;
}
}
Then create Player
objects and store them in an ArrayList
. Don't use an array unless you know how many players are going to be added.
List<Player> players = new ArrayList<Player>();
if (control == 1) {
String name = JOptionPane.showInputDialog(null, "New player: ", "Add New Player",
JOptionPane.INFORMATION_MESSAGE);
int attendance = Integer.parseInt(JOptionPane.showInputDialog(null,
"How many matchs have he played so far? ", "Attendance", JOptionPane.INFORMATION_MESSAGE));
Player player = new Player(name, attendance);
players.add(player);
} else if (control == 2) {
for (int i = 0; i < players.size(); i++) {
Player player = players.get(i);
JOptionPane.showMessageDialog(null, "Attendance = " + player.getAttendance(), "N: " + i + "- " + player.getName(),
JOptionPane.WARNING_MESSAGE);
}
}
精彩评论