-5

I'm coding a simulation of a sports game, and it works fine for the most part; compiles and runs like it should. The directions ask that I I assume that I am supposed to be using printf and %.2f, but whenever I try to incorporate that into my code, it ceases to run properly. Help would be much appreciated!

import java.util.Scanner;

public class Team {

public String name;

public String location;

public double offense;

public double defense;

public Team winner;

public Team(String name, String location) {
  this.name = name;
  this.location = location;
  this.offense = luck();
  this.defense = luck();
}     

public double luck() {
    return Math.random();
}

Team play(Team visitor) {
    Team winner;
    double home;
    double away;
    home = (this.offense + this.defense + 0.2) * this.luck();
    away = (visitor.offense + visitor.defense) * visitor.luck();
    if (home > away)
      winner = this;
    else if (home < away)
      winner = visitor;
    else
      winner = this;
    return winner;
}

public static void main(String[] args) {
  Scanner s = new Scanner(System.in);
    System.out.println("Enter name and location for home team (on separate lines)");
                         String homeName = s.next();
                         String homeLocation = s.next();
                         Team homeTeam = new Team(homeName, homeLocation);
    System.out.println("Enter name and location for home team (on separate lines)");
                         String awayName = s.next();
                         String awayLocation = s.next();
                         Team awayTeam = new Team(awayName, awayLocation);
    Team winnerTeam = homeTeam.play(awayTeam);
    System.out.printf("Home team is:" + homeName + " from" + homeLocation + " rated" + homeTeam.offense + " (offense) +" + homeTeam.defense + " (defense)" + "\n");
    System.out.printf("Away team is:" + awayName + " from" + awayLocation + " rated" + awayTeam.offense + " (offense) +" + awayTeam.defense + " (defense)" + "\n");
    System.out.printf("Winner is:" + winnerTeam.name + " from" + winnerTeam.location + " rated" + winnerTeam.offense + " (offense) +" + winnerTeam.defense + " (defense)" + "\n");
}
  • What does "*it ceases to run properly*" actually mean? Where's that part of the code that gives you a trouble? – PM 77-1 Sep 17 '13 at 01:37
  • "It ceases to run properly" is not acceptable as a problem description. Try again. – user207421 Sep 17 '13 at 01:37
  • Oh, my apologies. It gives the following errors: – Kevin Roberts Sep 17 '13 at 01:38
  • Same question as: http://stackoverflow.com/questions/18839245/printing-to-two-decimal-points-and-help-starting-winner-code#comment27793783_18839245 – Hovercraft Full Of Eels Sep 17 '13 at 01:39
  • That's not how you do `printf(...)`, and in fact the whole reason for using `System.out.printf(...)` is to avoid explicit String concatenation. Please read the tutorial as it's explained there. – Hovercraft Full Of Eels Sep 17 '13 at 01:40
  • And tutorial is [here](http://docs.oracle.com/javase/tutorial/java/data/numberformat.html). – PM 77-1 Sep 17 '13 at 01:43
  • possible duplicate of [How to round a number to n decimal places in Java](http://stackoverflow.com/questions/153724/how-to-round-a-number-to-n-decimal-places-in-java) – Dawood ibn Kareem Sep 17 '13 at 01:55
  • @HovercraftFullOfEels - well, if one member of the class is getting help with his homework, it's only fair that they all should. – Dawood ibn Kareem Sep 17 '13 at 01:57
  • Well, I don't see how I am doing printf wrong to begin with. I'm trying to get the values of offense and defense to print to two decimal spaces using that method, but all my attempts to use it have ended in the program not being able to run at all. The program works fine when I am not attempting to do this. – Kevin Roberts Sep 17 '13 at 02:06

2 Answers2

2

You have misunderstood the printf method. You do not concatenate strings the way you do in this line and its successors (reformatted for width reasons):

 System.out.printf("Home team is:" + homeName +
                   " from" + homeLocation +
                   " rated" +  homeTeam.offense +
                   " (offense) +" + homeTeam.defense +
                   " (defense)" + "\n");

This is like the way an old coworker tried to use PreparedStatements to prevent SQL injection attacks, but constructed the query string by concatenation anyway, making the attempt ineffective. Instead, look at the signature of printf:

public PrintWriter format(String format, Object... args)

The first argument is a format string, which contains static text and format directives beginning with %. In typical use, each format directive corresponds to one argument of the method. Replace the interpolated variables with directives.

Strings are usually formatted with %s: s for string. Doubles are usually formatted with %f: f for float (or double). Characters between the % and the letter are options. So, let's replace the strings you interpolated with directives:

"Home team is: "  + "%s" +             // Inserted a space.
" from"           + "%s" +
" rated"          + "%6.2f" +          // Six characters, 2 after the decimal.
" (offense)    +" + "%6.2f" +
" (defense)"      + "%n"               // %n means the appropriate way to get a new line
                                       // for the encoding.

Now we put it all together:

System.out.format("Home team is: %s from %s rated %6.2f (offense) + %6.2f (defense)%n",
                   homeName, homeLocation, homeTeam.offense, homeTeam.defense);

This is a lot simpler. Additionally, another reason to avoid interpolating strings in a format string is that the strings you interpolate may contain a percent sign itself. See what happens if you unguardedly write this:

String salesTax = "5%";
System.out.format("The sales tax is " + salesTax);

That's equivalent to

System.out.format("The sales tax is 5%");

Unfortunately, the percent sign is treated as a format directive, and the format statement throws an exception. Correct is either:

System.out.format("The sales tax is 5%%");

or

String salesTax = "5%";
System.out.format("The sales tax is %s", salesTax);

But now I should ask why you did not take homeName and homeLocation from Team. Certainly they are more relevant to Team than to each other. In fact, you should look up the Formattable interface, and with proper coding you can write:

System.out.format("%s%, homeTeam); 
Eric Jablow
  • 7,874
  • 2
  • 22
  • 29
  • Great answer. Explained this very clearly to me. As for your question at the end, I'm not really sure. Would it be more efficient for me to take homeName and homeLocation from Team, and how would I go about doing that? – Kevin Roberts Sep 17 '13 at 02:20
  • It's not a matter of easier or harder. It's a matter of what you would understand if you had to read this code again in 6 months. As a student, that probably won't happen. As part of a job, it will. – Eric Jablow Sep 17 '13 at 02:41
  • Oh, I see. That sounds pretty useful to have that knowledge at a glance. I haven't learned Formattable yet in class, but I'll look into it. – Kevin Roberts Sep 17 '13 at 02:45
1

Try this:

public class A {
  public static void main(String[] args) {
    System.out.println(String.format("%.2f", 12.34123123));
  }
}
mabn
  • 2,473
  • 1
  • 26
  • 47