这是我在这个网站上的第一篇文章,所以请耐心:) 我正在研究java,我正在尝试创建一个小程序,在两个数组中存储播放器的名称和它们的出席。我正在使用JOptionPane作为'用户界面'。当用户要求时,我希望显示他们的名字和相应的出席情况。 这是我的代码(它没有完成):
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.INFORMATION_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));
}
}
}
}
答案 0 :(得分:1)
而不是有两个数组;一个用于玩家,一个用于出席,通过创建一个封装了玩家姓名和出勤率的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;
}
}
然后创建Player
个对象并将其存储在ArrayList
中。除非你知道要添加多少玩家,否则不要使用数组。
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);
}
}