почему следующий код не дает правильного вывода? - PullRequest
0 голосов
/ 01 ноября 2019

Вас попросили разработать отчет о прохождении и получении статистики Национальной футбольной лиги (НФЛ) с использованием кода Java. Квотербеки и широкие получатели имеют некоторую общую информацию, но другая информация зависит от их положения.

Класс игрока

public class Player {

    String firstName; 
    String lastName; 
    String team;
    String position;

    public Player(String firstName, String lastName, String team, String position) 
    {
        super();
        this.firstName = firstName;
        this.lastName = lastName;
        this.team = team;
        this.position = position;
    }

    public String getFirstName()
    {
        return firstName;
    }

    public void setFirstName(String firstName) 
    {
        this.firstName = firstName;
    }

    public String getLastName()
    {
        return lastName;
    }

    public void setLastName(String lastName)
    {
        this.lastName = lastName;
    }

    public String getTeam() 
    {
        return team;
    }

    public void setTeam(String team) 
    {
        this.team = team;
    }

    public String getPosition() 
    {
        return position;
    }

    public void setPosition(String position) 
    {
        this.position = position;
    }
} 

Класс квотербека

public class Quarterback extends Player {
    int completions; 
    int attempts;
    int yards;

    public Quarterback(String firstName, String lastName, String team,
            String position, int completions, int attempts, int yards) 
    {

        super(firstName, lastName, team, position);
        this.completions = completions;
        this.attempts = attempts;
        this.yards = yards;
    }

    public int getCompletions() 
    {
        return completions;
    }

    public void setCompletions(int completions) 
    {
        this.completions = completions;
    }

    public int getAttempts() 
    {
        return attempts;
    }

    public void setAttempts(int attempts)
    {
        this.attempts = attempts;
    }

    public int getYards() 
    {
        return yards;
    }

    public void setYards(int yards)
    {
        this.yards = yards;
    }

    public double percent() 
    {
        return ((double) completions / (double) attempts) * 100.0d;
    }

    public double yardsPerAttempt() 
    {
        return (double) yards / (double) attempts;
    }

    public double yardsPerGame() 
    {
        return (double) yards / (double) 16.0d;
    }
}

Класс получателя

public class Receiver extends Player{
    int receptions;
    int yards;
    public Receiver(String firstName, String lastName, String team,
            String position, int receptions, int yards) 
    {
        super(firstName, lastName, team, position);
        this.receptions = receptions;
        this.yards = yards;
    }

    public int getReceptions()
    {
        return receptions;
    }

    public void setReceptions(int receptions) 
    {
        this.receptions = receptions;
    }

    public int getYards()
    {
        return yards;
    }

    public void setYards(int yards)
    {
        this.yards = yards;
    }

    public double yardsPerReception() 
    {
        return (double) yards / (double) receptions;
    }

    public double yardsPerGame() 
    {
        return (double) yards / 16.0d;
    }
}

Ниже моя проблема с выводом данных.

import java.io.File;
import java.util.Scanner;

public class NFLTestPlayer 
{

    public static void main(String[] args) 
    {
        Scanner scanner = null;

        try 
        {
            Player players[] = new Player[20];
            scanner = new Scanner(new File("nfl.txt"));
            int count = 0;


            while (scanner.hasNext())
            {
                String firstName, lastName, team, position;
                firstName = scanner.next();
                lastName = scanner.next();
                team = scanner.next();
                position = scanner.next();

                if (position.equals("QB")) 
                {
                    int completions, attempts, yards;
                    completions = scanner.nextInt();
                    attempts = scanner.nextInt();
                    yards = scanner.nextInt();

                    players[count++] = new Quarterback(firstName, lastName,
                            team, position, completions, attempts, yards);
                    } 
                else if (position.equals("WR")) 
                {
                    int receptions;
                    int yards;
                    receptions = scanner.nextInt();
                    yards = scanner.nextInt();
                    players[count++] = new Receiver(firstName, lastName, team,
                            position, receptions, yards);
                    }
                }
            System.out.println("NFL 2018 Player Passing/Receiving Statistics\n");
            System.out.println("Quarterbacks");

            System.out.printf("%-25s %-5s %12s %12s %12s %12s %12s %12s\n",
                    "Player","Team", "Comp","Att","Pct","Yds","Yds/A","Yds/G");

            for (int i = 0; i < players.length; i++)
            {
                if (players[i] instanceof Quarterback) 
                {
                    Quarterback quarterback = (Quarterback) players[i];
                    System.out.printf("%-25s %-5s %12.0f %12.0f %12.0f %12.1f %12.2f %12d",
                            quarterback.getFirstName() 
                            + ","  + quarterback.getLastName() 
                            + quarterback.getTeam()
                            + quarterback.getCompletions()
                            + quarterback.getAttempts()

                            + quarterback.getYards()
                            +quarterback.yardsPerAttempt() 
                            +quarterback.yardsPerGame());
                    }
                }

            System.out.println("\n");
            System.out.println("Wide Receivers");
            System.out.printf("%-25s %-5s %12s %12s %12s %12s\n",
                    "Player","Team", "Rec", "Yds","Yds/R","Yds/G");


            for (int i = 0; i < players.length; i++) 
            {
                if (players[i] instanceof Receiver)
                {
                    Receiver receiver = (Receiver) players[i];
                    System.out.printf("%-25s %-5s %12.0f %12.0f %12.0f %12.1f",
                            receiver.getFirstName()
                            + ","  + receiver.getLastName()
                            + receiver.getTeam()
                            + receiver.getReceptions()
                            + receiver.getYards()
                            + receiver.yardsPerReception()
                            + receiver.yardsPerGame());
                    }
                }
            } catch (Exception e)
        {
                e.printStackTrace();        
        }
    }
}

вывод должен создать таблицу с использованием следующего текстового файла:

nfl.txt

Ben Roethlisberger PIT QB 452 675 5129
Julio Jones ATL WR 113 1677 
Aaron Rodgers GB QB 372 597 4442
Patrick Mahomes KC QB 383 580 5097
JuJuj Smith-Schuster PIT WR 111 1426 
Philip Rivers LAC QB 347 508 4308
DeAndre Hopkins HOU WR 115 1572 
Mike Evans TB WR 86 1524 
Matt Ryan ATL QB 422 608 4924
Davante Adams GB WR 111 1386 
Tyreek Hill KC WR 87 1479 
Michael Thomas NO WR 125 1405 
Jared Goff LAR QB 364 561 4688
Andrew Luck IND QB 430 639 4593
Adam Thielen MIN WR 113 1373 
Eli Manning NYG QB 380 576 4299
Kirk Cousins MIN QB 425 606 4298
Robert Woods LAR WR 86 1219 
Tom Brady NE QB 375 570 4355
Brandin Cooks LAR WR 80 1204


NFL 2018 Player Passing/Receiving Statistics            
Quarterbacks                            
Player         Team Comp Att Pct    Yds    Yds/A  Yds/6
Brady,Tom       NE  375 570  66.    4,355   8.     272
Cousins,Kirk    MIN 425 606  70.    4,298   7.     268
Goff,jared      LAR 364 561  65.    4,688   8.     293
Luck,Andrew     IND 430 639  67.    4,593   7.     287
Mahomes,Patrick KC  383 580  66.0   5,097   9.     318
Manning,Eli     NYG 380 576  66.0   4,299   7.     268
Rivers,Philip   LAC 347 508  68.    4,308   8.     269
Rodgers,Aaron   GB  372 597  62.    4,442   7.     277
Roethlisberger, PIT 452  675 67.0   5,129   7.60    320
Ryan,Matt       ATL 422 608  69.    4,924   8.10    307

Receivers                           
Player              Team    Rec  Yds   Yds/R    Yds/6       
Adams,Davante        G8     111 1,386   13.      87.        
Cooks,Brandin       LAR     80  1,204   15.      75.        
Evans,Mike           TB     86  1,524   18.      95.        
Hill,Tyreek          KC     87  1,479   17.0    92.     
Hopkins,DeAndre      HOU    115 1,572   14.     98.     
lonesOullo           ATL    113 1,677   15.     105.        
Smith-Schuster,JuJu PIT     111 1,426   13.     89.     
Thielen,Adam        KIN     113 1,373   12.     86.     
Thomas,Michael      NO      125 1,405   11.     88.     
Woods,Robert        LAR     86  1,219   14.     76.     

1 Ответ

0 голосов
/ 01 ноября 2019

Не могли бы вы немного прояснить и объяснить, с какой проблемой вы сталкиваетесь? Вы получаете какую-то ошибку? Или вывод не тот же?

Я выхожу на конечность и задаюсь вопросом, есть ли у вас исключение java.util.MissingFormatArgumentException?

Редактировать:

Хорошо, есть причина для этого - вы неправильно форматировать. Это дубликат другого вопроса: java.util.MissingFormatArgumentException: спецификатор формата: s

Но для облегчения вашей жизни вот ответ

System.out.printf("%-25s %-5s %12.0f %12.0f %12.0f %12.1f %12.2f",
                        quarterback.getFirstName() + " " + quarterback.getLastName(), quarterback.getTeam(), (double)quarterback.getCompletions(), (double)quarterback.getAttempts(), (double)quarterback.getYards(), quarterback.yardsPerAttempt(), quarterback.yardsPerGame());
System.out.println("/n");

Однако,Я настоятельно рекомендую вам ознакомиться с форматированием с использованием спецификаторов. Причина, по которой вы получили это исключение, заключается в том, что вы неправильно связали свои переменные с вашими спецификаторами.

...