【发布时间】:2021-04-04 05:52:34
【问题描述】:
此程序有效,但我不确定为什么使用ArrayList 的方法必须在方法标头中包含static。仅作为背景,该程序接收一个文本文件,读取它并将其内容保存到ArrayList<Game>(游戏)中。用户输入文件名和球队名,程序会输出该球队打了多少场比赛,赢了多少场,输了多少场。
它读取的 .csv 格式如下:
ENCE,Vitality,9,16
ENCE,Vitality,16,12
etc..
以下所有四种方法,一种方法返回ArrayList,另外三种返回ints,除非我在方法标题中输入关键字static,否则将不起作用。如果我只为方法写public ArrayList<Game>或public int,它们将不起作用。
在任何时候将Arraylist 传递到方法中是否意味着方法标头必须始终包含static?为什么会这样?
这是工作代码:
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Scanner;
public class SportStatistics {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("File: ");
String file = scan.nextLine();
ArrayList<Game> record = getGame(file); //After method returns the list of
objects, it is copied over to another list.
System.out.println("Team: ");
String team = scan.nextLine();
//These methods return how many games a team played, has won and has lost.
int gamesPlayed = getGamesPlayed(record, team);
int gamesWon = getGamesWon(record, team);
int gamesLost = getGamesLost(record, team);
System.out.println("Games: " + gamesPlayed);
System.out.println("Wins: " + gamesWon);
System.out.println("Losses: " + gamesLost);
}
//This method takes in the file name given by user and saves file details into
a list of objects.
**public static** ArrayList<Game> getGame(String file){
ArrayList<Game> games = new ArrayList<>();
try(Scanner reader = new Scanner(Paths.get(file))){
while(reader.hasNextLine()){
String input = reader.nextLine();
String[] parts = input.split(",");
String homeTeam = parts[0];
String visitingTeam = parts[1];
int homePoints = Integer.valueOf(parts[2]);
int visitingPoints = Integer.valueOf(parts[3]);
games.add(new Game(homeTeam, visitingTeam, homePoints,
visitingPoints));
}
}
catch(Exception e){
System.out.println("Error: File " + file + " not found.");
}
return games;
}
**public static int** getGamesPlayed(ArrayList<Game> record, String team){
int gamesPlayed = 0;
for(Game game: record){
if (game.getHomeTeam().equals(team) ||
game.getVisitngTeam().equals(team)){
gamesPlayed++;
}
}
return gamesPlayed;
}
**public static int** getGamesWon(ArrayList<Game> record, String team){
int gamesWon = 0;
for(Game game: record){
if (game.getHomeTeam().equals(team) ||
game.getVisitngTeam().equals(team)){
if(game.getHomeTeam().equals(team) && game.getHomePoints() >
game.getVisitingPoints()){
gamesWon++;
}
if(game.getVisitngTeam().equals(team) && game.getVisitingPoints() >
game.getHomePoints()){
gamesWon++;
}
}
}
return gamesWon;
}
**public static int** getGamesLost(ArrayList<Game> record, String team){
int gamesLost = 0;
for(Game game: record){
if (game.getHomeTeam().equals(team) ||
game.getVisitngTeam().equals(team)){
if(game.getHomeTeam().equals(team) && game.getHomePoints() <
game.getVisitingPoints()){
gamesLost++;
}
if(game.getVisitngTeam().equals(team) && game.getVisitingPoints() <
game.getHomePoints()){
gamesLost++;
}
}
}
return gamesLost;
}
}
【问题讨论】:
标签: java arraylist methods compiler-errors static