使用以下代码实现从键盘上接收一个选手的学号 给他加分 package t8; import java.util.ArrayList; import java.util.Iterator; import t5.Player; public class ArrayListDemo { public static void main(String[] args) { ArrayList<Player> players = new ArrayList<Player>(); players.add(new Player("曾佳欣", "信息与通信", "22-1", "111")); players.add(new Player("罗曼君", "信息与通信", "22-1", "222")); players.add(new Player("张嘉颖", "信息与通信", "22-1", "333")); players.add(new Player("吴少景", "信息与通信", "22-1", "444")); System.out.println("联系方式\t姓名\t班级\t系部\t得分"); for (Player player : players) { System.out.println(player.getContact() + "\t" + player.getName() + "\t" + player.getCls() + "\t" + player.getAcademy() + "\t" + player.getScore()); } } }
时间: 2023-07-03 17:19:20 浏览: 107
java代码-import java.util.Scanner;
5星 · 资源好评率100%
可以使用如下代码实现从键盘上接收一个选手的学号,并给他加分:
```
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Scanner;
import t5.Player;
public class ArrayListDemo {
public static void main(String[] args) {
ArrayList<Player> players = new ArrayList<Player>();
players.add(new Player("曾佳欣", "信息与通信", "22-1", "111"));
players.add(new Player("罗曼君", "信息与通信", "22-1", "222"));
players.add(new Player("张嘉颖", "信息与通信", "22-1", "333"));
players.add(new Player("吴少景", "信息与通信", "22-1", "444"));
Scanner scanner = new Scanner(System.in);
System.out.print("请输入要加分的选手的学号:");
String id = scanner.next();
System.out.print("请输入要加的分数:");
int score = scanner.nextInt();
Iterator<Player> iter = players.iterator();
while (iter.hasNext()) {
Player player = iter.next();
if (player.getId().equals(id)) {
player.setScore(player.getScore() + score);
break;
}
}
System.out.println("联系方式\t姓名\t班级\t系部\t得分");
for (Player player : players) {
System.out.println(player.getContact() + "\t" + player.getName() + "\t" +
player.getCls() + "\t" + player.getAcademy() + "\t" + player.getScore());
}
scanner.close();
}
}
```
首先,我们引入`java.util.Scanner`类,用于从键盘上读取输入。然后,通过`Scanner`类的`next()`方法和`nextInt()`方法分别读取输入的选手学号和要加的分数。接着,我们通过`Iterator`迭代器遍历`ArrayList`中的每个选手,如果找到了指定学号的选手,则给他加分,并退出循环。最后,我们再次使用`for-each`循环输出所有选手的信息。需要注意的是,最后需要调用`Scanner`类的`close()`方法关闭输入流。
阅读全文