how to change toString() value - java

How do I make it so I'm able to change the jar1.toString() value and put it in the player.toString() value.
my programs output:
"Jill[](1) [a#1](1) [b#2](2) [c#3](3) /7\(4)"
desired output when using turn() method:
"Jill[a#1](1) [](1) [b#2](2) [c#3](3) /7\(4)"
I've already made it so that when a player inputs the string "P" for pickup, it deletes the value in the 1st jar "[](1) [b#2](2) [c#3](3)", I did this by making stone null and doing an if statement under the jar class java if stone == null we return the empty brackets [] but it is yet to transfer it to the player.toString() jar "Jill[](1)"
i've tried implementing if statements for Class Player String toString() method,
public String toString() {
return name + "[" + "]" + "(" + position + ")";
}
something along the lines of
return name + "[" + stone.toString() "]" + "(" + position + ")";
public class Ground
{
public Jar jar1;
private Jar jar2;
private Jar jar3;
private Player player;
private Chest chest;
private String move;
public String toString(){
return player.toString() + " " +
jar1.toString() + " " +
jar2.toString() + " " +
jar3.toString() + " " +
"/" + chest.combination + "\\" + "(" + chest.getPosition() + ")";
}
public void turn(){
System.out.print("Move (l/r/p/d): ");
move = Global.keyboard.nextLine();
if (move.equals("p") && player.getPosition() == jar1.getPosition()){
jar1 = new Jar(1, null);
}
public class Jar
{
private int position;
private Stone stone;
private Player pos;
public String toString() {
if (stone == null) {
return "[]" + "(" + getPosition() + ")";
}
return "[" + stone.toString() + "]" + "(" + getPosition() + ")";
}
public class Player
{
private String name;
private int position;
private static Jar jar;
private Stone stone;
private Ground ground;
public String toString() {
return name + "[" + "]" + "(" + position + ")";
}
public class Stone
{
private String name;
private int weight;
public Stone()
{
System.out.print("Enter stone name: ");
name = Global.keyboard.nextLine();
System.out.print("Enter stone weight: ");
weight = Global.keyboard.nextInt();
Global.keyboard.nextLine();
}
public String toString()
{
return name + "#" + weight;
}

Change Player.toString to include the player's stone. Also add a stone setter if you don't already have one:
public class Player {
private String name;
private int position;
private static Jar jar;
private Stone stone;
private Ground ground;
public String toString() {
return name + "[" + stone + "]" + "(" + position + ")";
}
public void setStone(Stone s) {
stone = s;
}
}
Add a stone getter to the Jar if you don't already have one:
public class Jar
{
private int position;
private Stone stone;
private Player pos;
public String toString() {
if (stone == null) {
return "[]" + "(" + getPosition() + ")";
}
return "[" + stone.toString() + "]" + "(" + getPosition() + ")";
}
public Stone getStone() {
return stone;
}
And when the player takes the turn, have them pick up the stone:
public void turn() {
System.out.print("Move (l/r/p/d): ");
move = Global.keyboard.nextLine();
if (move.equals("p") && player.getPosition() == jar1.getPosition()) {
player.setStone(jar1.getStone());
jar1 = new Jar(1, null);
}
}

Related

Java vanClass giving cannot find symbol error [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
I have code that has several classes with different cars and some classes. Below is my code, I'm not sure why vanClass van; is not working as it is basically a copy paste of the past classes that work. Any help is appreciated. To clarify, I am only having problems with the last few lines of the autopark class where I initiate vanClass as van and go from there.
import java.util.*;
class sedan {
String make;
String model;
String color;
int year;
double price;
boolean fourWD;
boolean isheavyDuty;
String carries;
public sedan(String initMake, String initModel, String initColor, int initYear, double initPrice) {
make = initMake;
model = initModel;
color = initColor;
year = initYear;
price = initPrice;
}
#Override
public String toString() {
String name = "Sedan";
String main = (color + " " + make + " " + model + " " + name + " (" + year + ") costs $" + price);
return main;
}
}
class SUV {
String make;
String model;
String color;
int year;
double price;
boolean fourWD;
String carries;
public SUV(String initMake, String initModel, String initColor, int initYear, double initPrice, boolean initFourWD){
make = initMake;
model = initModel;
color = initColor;
year = initYear;
price = initPrice;
fourWD = initFourWD;
}
public String toString() {
String name = "SUV";
String main = new String();
if (fourWD) {
main = ("4WD " + color + " " + make + " " + model + " " + name + " (" + year + ") costs $" + price);
}
else {
main = (color + " " + make + " " + model + " " + name + " (" + year + ") costs $" + price);
}
return main;
}
}
class truckClass {
String make;
String model;
String color;
int year;
double price;
boolean fourWD;
boolean isheavyDuty;
String carries;
public truckClass(String initMake, String initModel, int initYear, double initPrice, boolean initisheavyDuty, String initCarries){
make = initMake;
model = initModel;
year = initYear;
price = initPrice;
isheavyDuty = initisheavyDuty;
carries = initCarries;
}
public String toString() {
String name = "Truck";
String main = (make + " " + model + " " + name + " (" + year + ") carries" + carries + " costs $" + price);
return main;
}
class vanClass {
String make;
String model;
int year;
double price;
boolean isCovered;
String carries;
public vanClass(String initMake, String initModel, int initYear, double initPrice, boolean initisCovered, String initCarries){
make = initMake;
model = initModel;
year = initYear;
price = initPrice;
isCovered = initisCovered;
carries = initCarries;
}
public String toString() {
String name;
String main;
if (isCovered()){
name = "covered Van";
String main = (make + " " + model + " " + name + " (" + year + ") carries" + carries + " costs $" + price);
}
else {
name = "Van";
String main = (make + " " + model + " " + name + " (" + year + ") carries" + carries + " costs $" + price);
}
return main;
}
}
public class autoPark {
public static void main(String args[]) {
sedan sedan1; // declaring cars object by name sedan1
sedan1 = new sedan("Ford" , "Model-1" , "white" , 2015, 20000); // initialising sedan1 using sedan constructor
System.out.println(sedan1); // printing sedan1 for invoking toString() method
SUV suv; // declaring cars object by name suv
suv = new SUV("Ford" , "Model-1" , "white" , 2015, 20000, true); // initialising suv using SUV constructor
System.out.println(suv); // printing suv for invoking toString() method
truckClass truck; //declaring cars object by name truck
truck = new truckClass("Ford" , "Model-1" , 2015, 20000, true, "2"); // initialising truck using truck constructor
System.out.println(truck); // printing truck for invoking toString() method
vanClass van;
van = new vanClass("Ford" , "Model-1" , 2015, 20000, true, "2";
System.out.println(van);
}
}
I came across 4 issues
missing } just before starting vanClass
missing ) after van = new vanClass("Ford" , "Model-1" , 2015, 20000, true, "2");
extra pair of parenthesis after isCovered which is a member data instead of method
Declaring main as String twice inside the toString method of SUV class
import java.util.*;
class sedan {
String make;
String model;
String color;
int year;
double price;
boolean fourWD;
boolean isheavyDuty;
String carries;
public sedan(String initMake, String initModel, String initColor, int initYear, double initPrice) {
make = initMake;
model = initModel;
color = initColor;
year = initYear;
price = initPrice;
}
#Override
public String toString() {
String name = "Sedan";
String main = (color + " " + make + " " + model + " " + name + " (" + year + ") costs $" + price);
return main;
}
}
class SUV {
String make;
String model;
String color;
int year;
double price;
boolean fourWD;
String carries;
public SUV(String initMake, String initModel, String initColor, int initYear, double initPrice, boolean initFourWD){
make = initMake;
model = initModel;
color = initColor;
year = initYear;
price = initPrice;
fourWD = initFourWD;
}
public String toString() {
String name = "SUV";
String main = new String();
if (fourWD) {
main = ("4WD " + color + " " + make + " " + model + " " + name + " (" + year + ") costs $" + price);
}
else {
main = (color + " " + make + " " + model + " " + name + " (" + year + ") costs $" + price);
}
return main;
}
}
class truckClass {
String make;
String model;
String color;
int year;
double price;
boolean fourWD;
boolean isheavyDuty;
String carries;
public truckClass(String initMake, String initModel, int initYear, double initPrice, boolean initisheavyDuty, String initCarries){
make = initMake;
model = initModel;
year = initYear;
price = initPrice;
isheavyDuty = initisheavyDuty;
carries = initCarries;
}
public String toString() {
String name = "Truck";
String main = (make + " " + model + " " + name + " (" + year + ") carries" + carries + " costs $" + price);
return main;
}
}
class vanClass {
String make;
String model;
int year;
double price;
boolean isCovered;
String carries;
public vanClass(String initMake, String initModel, int initYear, double initPrice, boolean initisCovered, String initCarries){
make = initMake;
model = initModel;
year = initYear;
price = initPrice;
isCovered = initisCovered;
carries = initCarries;
}
public String toString() {
String name;
String main;
if (isCovered){
name = "covered Van";
main = (make + " " + model + " " + name + " (" + year + ") carries" + carries + " costs $" + price);
}
else {
name = "Van";
main = (make + " " + model + " " + name + " (" + year + ") carries" + carries + " costs $" + price);
}
return main;
}
}
public class autoPark {
public static void main(String args[]) {
sedan sedan1; // declaring cars object by name sedan1
sedan1 = new sedan("Ford" , "Model-1" , "white" , 2015, 20000); // initialising sedan1 using sedan constructor
System.out.println(sedan1); // printing sedan1 for invoking toString() method
SUV suv; // declaring cars object by name suv
suv = new SUV("Ford" , "Model-1" , "white" , 2015, 20000, true); // initialising suv using SUV constructor
System.out.println(suv); // printing suv for invoking toString() method
truckClass truck; // declaring cars object by name truck
truck = new truckClass("Ford" , "Model-1" , 2015, 20000, true, "2"); // initialising truck using truck constructor
System.out.println(truck); // printing truck for invoking toString() method
vanClass van;
van = new vanClass("Ford" , "Model-1" , 2015, 20000, true, "2");
System.out.println(van);
}
}
You need to consider using inheritance as mentioned by others.
I fixed and refactored your class using inheritance:
abstract class Vehicle{
protected String maker;
protected String model;
protected int year;
protected double price;
public Vehicle(String maker, String model, int year, double price) {
this.maker=maker;
this.model=model;
this.year=year;
this.price=price;
}
abstract String getType();
#Override
public String toString() {
return maker + " " + model + " " + getType() + " (" + year + ") costs $" + price;
}
}
abstract class HeavyVehicle extends Vehicle{
protected String carries;
public HeavyVehicle(String maker, String model, int year, double price, String carries) {
super(maker, model, year, price);
this.carries=carries;
}
}
class SUV extends HeavyVehicle{
String color;
boolean fourWD;
public SUV(String maker, String model, String initColor, int year, double price,
boolean initFourWD) {
super(maker,model,year,price,"1");
color = initColor;
fourWD = initFourWD;
}
public String toString() {
StringBuilder sb = new StringBuilder();
if (fourWD) {
sb.append("4WD ");
}
sb.append(color + " " + super.toString());
return sb.toString();
}
#Override
String getType() {
return "SUV";
}
}
class Truck extends HeavyVehicle{
public Truck(String maker, String model, int year, double price,String carries) {
super(maker,model,year,price,carries);
}
public String toString() {
return maker + " " + model + " " + getType() + " (" + year + ") carries" + carries + " costs $" + price;
}
#Override
String getType() {
return "Truck";
}
}
class Van extends HeavyVehicle{
boolean isCovered;
public Van(String maker, String model, int year, double price, boolean isCovered, String carries){
super(maker,model,year,price,carries);
this.isCovered = isCovered;
}
public String toString() {
String name = isCovered ? "covered Van" : getType();
return maker + " " + model + " " + name + " (" + year + ") carries" + carries + " costs $" + price;
}
#Override
String getType() {
return "Van";
}
}
class Sedan extends Vehicle{
String color;
public Sedan(String maker, String model, String color, int year, double price) {
super(maker,model,year,price);
this.color = color;
}
#Override
public String toString() {
return color + " " + super.toString();
}
#Override
String getType() {
return "Sedan";
}
}
public class Main {
public static void main(String args[]) {
Sedan sedan1; // declaring cars object by name sedan1
sedan1 = new Sedan("Ford", "Model-1", "white", 2015, 20000); // initialising sedan1 using sedan constructor
System.out.println(sedan1); // printing sedan1 for invoking toString() method
SUV suv; // declaring cars object by name suv
suv = new SUV("Ford", "Model-1", "white", 2015, 20000, true); // initialising suv using SUV constructor
System.out.println(suv); // printing suv for invoking toString() method
Truck truck; // declaring cars object by name truck
truck = new Truck("Ford", "Model-1", 2015, 20000, "2"); // initialising truck using truck constructor
System.out.println(truck); // printing truck for invoking toString() method
Van van;
van = new Van("Ford", "Model-1", 2015, 20000, true, "2");
System.out.println(van);
}
}
Was missing a } and ). Silly mistake

How to Pair Up Random Indices of an ArrayList with each other

I am currently working on a project where I read in a CSV file that contains a list of Pokemon, as well as their traits. I am trying to run a battle simulator that randomly pairs up these Pokemon with each other and compares their combatScore, which is a result of a simple calculation using their traits such as speed, attack, defense, etc. I read in all of the Pokemon from the CSV file into an ArrayList of type Pokemon. Now, I want to randomly pair them up with each other and compare their combatScore; whoever has the higher score moves on to the next round, and the loser is placed into another ArrayList of defeated Pokemon. However, I do not know how to randomly pair up the Pokemon. Here is my code of the main class so far:
import java.io.*;
import java.util.ArrayList;
import java.util.Random;
public class assign1 {
public static void main(String[] args) throws IOException {
String csvFile = args[0]; //path to CSV file
String writeFile = args[1]; //name of output file that contains list of Pokemon and their traits
BufferedReader br = null;
String line = "";
String cvsSplitBy = ",";
ArrayList<Pokemon> population = new ArrayList<Pokemon>();
FileWriter fileWriter = new FileWriter(writeFile);
BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);
try {
br = new BufferedReader(new FileReader(csvFile));
String headerLine = br.readLine(); // used to read first line of CSV file that contains headers
while ((line = br.readLine()) != null) {
Pokemon creature = new Pokemon();
// use comma as separator
String[] pokemon = line.split(cvsSplitBy);
creature.setId(pokemon[0]);
creature.setName(pokemon[1]);
creature.setType1(pokemon[2]);
creature.setType2(pokemon[3]);
creature.setTotal(pokemon[4]);
creature.setHp(Integer.parseInt(pokemon[5]));
creature.setAttack(Integer.parseInt(pokemon[6]));
creature.setDefense(Integer.parseInt(pokemon[7]));
creature.setSpAtk(Integer.parseInt(pokemon[8]));
creature.setSpDef(Integer.parseInt(pokemon[9]));
creature.setSpeed(Integer.parseInt(pokemon[10]));
creature.setGeneration(Integer.parseInt(pokemon[11]));
creature.setLegendary(Boolean.parseBoolean(pokemon[12]));
creature.getCombatScore();
// Adds individual Pokemon to the population ArrayList
population.add(creature);
// Writes to pokemon.txt the list of creatures
bufferedWriter.write(creature.getId() + ". "
+ "Name: " + creature.getName() + ": "
+ "Type 1: " + creature.getType1() + ", "
+ "Type 2: " + creature.getType2() + ", "
+ "Total: " + creature.getTotal() + ", "
+ "HP: " + creature.getHp() + ", "
+ "Attack: " + creature.getAttack() + ", "
+ "Defense: " + creature.getDefense() + ", "
+ "Special Attack: " + creature.getSpAtk() + ", "
+ "Special Defense: " + creature.getSpDef() + ", "
+ "Speed: " + creature.getSpeed() + ", "
+ "Generation: " + creature.getGeneration() + ", "
+ "Legendary? " + creature.isLegendary() + ", "
+ "Score: " + creature.getCombatScore());
bufferedWriter.newLine();
}
}
catch (FileNotFoundException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
finally {
if (br != null) {
try {
br.close();
}
catch (IOException e) {
e.printStackTrace();
}
}
}
bufferedWriter.close();
}
}
And here is the code for my Pokemon class:
public class Pokemon {
String id;
String name;
String type1;
String type2;
String total;
int hp;
int attack;
int defense;
int spAtk;
int spDef;
int speed;
int generation;
boolean legendary;
public Pokemon() {}
public String getId () {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getType1() {
return type1;
}
public void setType1(String type1) {
this.type1 = type1;
}
public String getType2() {
return type2;
}
public void setType2(String type2) {
this.type2 = type2;
}
public String getTotal() {
return total;
}
public void setTotal(String total) {
this.total = total;
}
public int getHp() {
return hp;
}
public void setHp(int hp) {
this.hp = hp;
}
public int getAttack() {
return attack;
}
public void setAttack(int attack) {
this.attack = attack;
}
public int getDefense() {
return defense;
}
public void setDefense(int defense) {
this.defense = defense;
}
public int getSpAtk() {
return spAtk;
}
public void setSpAtk(int spAtk) {
this.spAtk = spAtk;
}
public int getSpDef() {
return spDef;
}
public void setSpDef(int spDef) {
this.spDef = spDef;
}
public int getSpeed() {
return speed;
}
public void setSpeed(int speed) {
this.speed = speed;
}
public int getGeneration() {
return generation;
}
public void setGeneration(int generation) {
this.generation = generation;
}
public boolean isLegendary() {
return legendary;
}
public void setLegendary(boolean legendary) {
this.legendary = legendary;
}
public int getCombatScore() {
return (speed/2) * (attack + (spAtk/2)) + (defense + (spDef/2));
}
#Override
public String toString() {
return "Name: " + this.getName()
+ ", Type 1: " + this.getType1()
+ ", Type 2: " + this.getType2()
+ ", Total: " + this.getTotal()
+ ", HP: " + this.getHp()
+ ", Attack: " + this.getAttack()
+ ", Defense: " + this.getDefense()
+ ", Sp. Attack: " + this.getSpAtk()
+ ", Sp. Defense: " + this.getSpDef()
+ ", Generation: " + this.getGeneration()
+ ", Legnedary: " + this.isLegendary()
+ ", Score: " + this.getCombatScore();
}
}
I only want to compare their combatScore values to each other. Any help/suggestions would be much appreciated.
What come to my mind is this. You pick one random item (pokemon) from array list. Remove it from array list. Then you pick one random item again and remove it. Now you have a pair of items. Repeat above step for remaining items in array list until no more items available.
Or you can shuffle whole array list first and then pick item i and item i+1 as pair for i=0,2,4,6,...
Collections.shuffle(pokemonsArrayList);
for (int i=0; i< pokemonsArrayList.size(); i+=2) {
pokemon1 = pokemonsArrayList.get(i);
pokemon2 = pokemonsArrayList.get(i+1);
}
Just make sure that number of elements in ArrayList is even. Otherwise code above will throw exception index out of bound
Since every element in an ArrayList has an index, you can just get a random element from it by calling
Pokemon pokemon1;
Pokemon pokemon2;
pokemon1 = arrayList.get(Math.random()*arrayList.size());
do {
pokemon2 = arrayList.get(Math.random()*arrayList.size());
} while(pokemon1.getId() == pokemon2.getId());
then compare the Pokémon you got out of List1 with the one you got from List2.
You can then of course remove the Pokémon from the List if you wish.
Hope that helps you out!

Parse Youtube JSONC with GSON

i know how to parse Json in android. but i can't seem to wrap my head around parsing JSONC from Youtube using GSON. i just need to parse the title of the video. Thanks here is the url
http://gdata.youtube.com/feeds/api/videos/iS1g8G_njx8?v=2&alt=jsonc
The following code works to parse the given response with Gson
public class ExampleParser {
public static final String JSONC =
"{\"apiVersion\":\"2.1\","
+ " \"data\":{"
+ " \"id\":\"iS1g8G_njx8\","
+ " \"uploaded\":\"2014-05-30T20:00:01.000Z\","
+ " \"updated\":\"2014-11-26T14:14:11.000Z\","
+ " \"uploader\":\"arianagrandevevo\","
+ " \"category\":\"Music\","
+ " \"title\":\"Ariana Grande - Problem ft. Iggy Azalea\","
+ " \"description\":\"Ariana Grande ft. Iggy Azalea - Problem\nBuy now! http://smarturl.it/ArianaMyEvrythnDlxiT?IQid=vevo.cta.problem\nGoogle Play: http://goo.gl/n7rey5\n\nPre-order My Everything and get access to the iHeartRadio Concert video stream where Ariana performs songs from her new album FOR THE FIRST TIME!\nhttp://myplay.me/19ys\","
+ " \"thumbnail\":{"
+ " \"sqDefault\":\"http://i.ytimg.com/vi/iS1g8G_njx8/default.jpg\","
+ " \"hqDefault\":\"http://i.ytimg.com/vi/iS1g8G_njx8/hqdefault.jpg\"},"
+ " \"player\":{"
+ " \"default\":\"http://www.youtube.com/watch?v=iS1g8G_njx8&feature=youtube_gdata_player\"},"
+ " \"content\":{"
+ " \"5\":\"http://www.youtube.com/v/iS1g8G_njx8?version=3&f=videos&app=youtube_gdata\"},"
+ " \"duration\":208,"
+ " \"aspectRatio\":\"widescreen\","
+ " \"rating\":4.731269,"
+ " \"likeCount\":\"1527921\","
+ " \"ratingCount\":1637964,"
+ " \"viewCount\":307368910,"
+ " \"favoriteCount\":0,"
+ " \"commentCount\":156682,"
+ " \"status\":{"
+ " \"value\":\"restricted\","
+ " \"reason\":\"limitedSyndication\"},"
+ " \"restrictions\":["
+ " {\"type\":\"country\","
+ " \"relationship\":\"deny\","
+ " \"countries\":\"DE\"}],"
+ " \"accessControl\":{"
+ " \"comment\":\"allowed\","
+ " \"commentVote\":\"allowed\","
+ " \"videoRespond\":\"moderated\","
+ " \"rate\":\"allowed\","
+ " \"embed\":\"allowed\","
+ " \"list\":\"allowed\","
+ " \"autoPlay\":\"allowed\","
+ " \"syndicate\":\"allowed\"}}}";
public static void main(String[] args) {
Gson gson = new GsonBuilder()
// Add your date deserializer
.create();
YoutubeResponse response = gson.fromJson(JSONC, YoutubeResponse.class);
System.out.println(response);
}
public static class YoutubeResponse {
Double apiVersion;
Data data;
}
public static class Data {
String id;
String uploaded; // TODO should be a date
String updated; // TODO should be a date
String uploader;
String category;
String title;
String description;
Thumbnail thumbnail;
Player player;
Integer duration;
String aspectRatio;
Double rating;
Integer likeCount;
Integer ratingCount;
Integer viewCount;
Integer favoriteCount;
Integer commentCount;
Status status;
List<Restriction> restrictions;
}
public static class Thumbnail {
String sqDefault;
String hqDefault;
}
public static class Player {
#SerializedName("default")
String defaultt; // default is a reserved java keyword
}
public static class Status {
String value;
String reason;
}
public static class Restriction {
String type;
String relationship;
String countries;
}
public static class AccessControl {
String comment;
String commentVote;
String videoRespond;
String rate;
String embed;
String list;
String autoPlay;
String syndicate;
}
}

How can I print out in columns in java

This is where I am printing out and I need it to print in columns.aLeaderboard is an array list with a custom class.it contains several different ints
System.out.println("Position Team Games Played Home Wins Home Draws Home Losses Home Goals For Home Goals Against Away Wins Away Draws Away Losses Away Goals For Away Goals Against Goal Difference Total Points");
for(int counter = 0;counter<teamName.size();counter++)
{
System.out.print((counter + 1) + " " + teamName.get(counter) + " " + (aLeaderboard.get(counter)).getGamesPlayed() + " " + (aLeaderboard.get(counter)).getHomeWins() + " " + (aLeaderboard.get(counter)).getHomeDraws() + " ");
System.out.print((aLeaderboard.get(counter)).getHomeLosses() + " " + (aLeaderboard.get(counter)).getAwayWins() + " " + (aLeaderboard.get(counter)).getAwayWins() + " " + (aLeaderboard.get(counter)).getAwayDraws() + " ");
System.out.print((aLeaderboard.get(counter)).getHomeGoalsFor() + " " + (aLeaderboard.get(counter)).getHomeGoalsAgainst() + " " + (aLeaderboard.get(counter)).getAwayLosses() + " " + (aLeaderboard.get(counter)).getGamesPlayed() + " ");
System.out.print((aLeaderboard.get(counter)).getAwayGoalsFor() + " " + (aLeaderboard.get(counter)).getAwayGoalsAgainst() + " " + (aLeaderboard.get(counter)).getGoalsDifference() + " " + (aLeaderboard.get(counter)).getTotalPoints());
System.out.println();
}
I would use System.out.printf(...) and use a template String to help be sure that all columns line up. Then you could print things out easily in a for loop.
For example:
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.List;
public class Foo4 {
public static void main(String[] args) {
List<Bar4> bar4List = new ArrayList<>();
bar4List.add(new Bar4("Donald", 3, "A", 22.42));
bar4List.add(new Bar4("Duck", 100, "B", Math.PI));
bar4List.add(new Bar4("Herman", 20, "C", Math.sqrt(20)));
String titleTemplate = "%-10s %6s %6s %9s%n";
String template = "%-10s %6d %6s %9s%n";
System.out.printf(titleTemplate, "Name", "Value", "Grade", "Cost");
for (Bar4 bar4 : bar4List) {
System.out.printf(template, bar4.getName(),
bar4.getValue(), bar4.getGrade(), bar4.getCostString());
}
}
}
class Bar4 {
private String name;
private int value;
private String grade;
private double cost;
private NumberFormat currencyFormat = NumberFormat.getCurrencyInstance();
public Bar4(String name, int value, String grade, double cost) {
this.name = name;
this.value = value;
this.grade = grade;
this.cost = cost;
}
public String getName() {
return name;
}
public int getValue() {
return value;
}
public String getGrade() {
return grade;
}
public double getCost() {
return cost;
}
public String getCostString() {
return currencyFormat.format(cost);
}
}
Which would return:
Name Value Grade Cost
Donald 3 A $22.42
Duck 100 B $3.14
Herman 20 C $4.47
For more details on the user of the String format specifiers (i.e., the %6d and %6s above), please look at the Formatter API.

Object Array won't print correctly [duplicate]

This question already has answers here:
How do I print my Java object without getting "SomeType#2f92e0f4"?
(13 answers)
Closed 7 years ago.
I'm brand new to programming and Java, I'm doing a school project with very strict guidelines. I'm sure there's a more efficient way to do my code, but that's not my issue. When I try to print my array at the bottom of main, I get
"Country#10b28f30, Country#3ad6a0e0, Country#60dbf04d",.... and so on.
I know the array is loading, because when
// System.out.println ("object is: " + name + " " + capital + " " + region + " " + region_Nbr + " " + capital_population);
runs, it prints all elements of the array as it's being built. I've keep reading something
about having to override toString, I've tride multiple ways to print the array, none work. Thanks in advance.
public class Main {
/**
* #param args the command line arguments
*/
private int size = 43;
private static Country[] countryInfo = new Country[43];
private Control control;
public static void main(String[] args) throws IOException {
String name = "";
String capital = "";
String region = "";
int region_Nbr = 0;
int capital_population = 0;
// TODO code application logic here
String filename = "Countries.txt";
String inputString;
FileInputStream fis1 = new FileInputStream(filename);
BufferedReader br1 = new BufferedReader(new InputStreamReader(fis1));
inputString = br1.readLine();
int count = 0;
while (inputString != null) {
//System.out.print(inputString + "\n");
name = inputString.substring(0, 13).trim();
//System.out.print(name + ", "); //echo
capital = inputString.substring(24, 36).trim();
//System.out.print(capital + ", ");//echo
region = inputString.substring(40, 56).trim();
//System.out.print(region + ", "); //echo
region_Nbr = Integer.parseInt(inputString.substring(64, 66).trim());
//System.out.print(region_Nbr + ", ");//echo
capital_population = Integer.parseInt(inputString.substring(72, inputString.length()).trim());
//System.out.print(capital_population + "\n");
countryInfo[count] = new Country(name, capital, region, region_Nbr, capital_population);
//Control.printArray(countryInfo);
inputString = br1.readLine();
count++;
} //end while
br1.close();
System.out.println(Arrays.toString(countryInfo));
}
}// end class Main
import java.util.Arrays;
public class Country
{
private String name;
private String capital;
private String region;
private int region_Nbr;
private int capital_population;
private Control control;
public Country (String strName, String strCapital,String strRegion, int iregion_Nbr, int icapitalpop)
{
name = strName;
capital = strCapital;
region = strRegion;
region_Nbr = iregion_Nbr;
capital_population = icapitalpop;
// System.out.println ("object is: " + name + " " + capital + " " + region + " " + region_Nbr + " " + capital_population);
}// end constructor
}//end class
}//end class
Since you want to print the elements of a Custom Class i.e Country in you case , you will need to override the toString implementation in the Country class.
If you do not override the toString for a custom class, it will print you the reference .
#Override
public String toString() {
return "Country: name = " + this.name + "; capital = " + this.capital + "; region = " + this.region ;
}
Why don't you use this
List<Country> countryInfoList = new ArrayList<Country>();
.....
and then just add the country to the countryInfoList i.e countryInfoList.add(country);
p.s: in both cases, you will have to override the toString implementation.
Every class has a toString method by default. You can override this method to return a more meaningful String value.
import java.util.Arrays;
public class Country
{
private String name;
private String capital;
private String region;
private int region_Nbr;
private int capital_population;
private Control control;
public Country (String strName, String strCapital,String strRegion, int iregion_Nbr, int icapitalpop)
{
name = strName;
capital = strCapital;
region = strRegion;
region_Nbr = iregion_Nbr;
capital_population = icapitalpop;
// System.out.println ("object is: " + name + " " + capital + " " + region + " " + region_Nbr + " " + capital_population);
}// end constructor
public String toString() {
return "Country: name = " + name + "; capital = " + capital + "; region = " + region + "; regionNbr = " + region_Nbr + "; population = " + capital_population;
}
}//end class
Obviously you can format the rely any way you want
Updated with working example...
import java.io.IOException;
import java.util.Arrays;
import java.util.ResourceBundle.Control;
public class Main {
private static Country[] countryInfo = new Country[1];
public static void main(String[] args) throws IOException {
new Main();
}
public Main() {
String name = "";
String capital = "";
String region = "";
int region_Nbr = 0;
int capital_population = 0;
countryInfo[0] = new Country("Australia", "Canberra", "AU", 61, 6000000);
System.out.println(Arrays.toString(countryInfo));
}
public class Country {
private String name;
private String capital;
private String region;
private int region_Nbr;
private int capital_population;
private Control control;
public Country(String strName, String strCapital, String strRegion, int iregion_Nbr, int icapitalpop) {
name = strName;
capital = strCapital;
region = strRegion;
region_Nbr = iregion_Nbr;
capital_population = icapitalpop;
}// end constructor
#Override
public String toString() {
return "Country: name = " + name + "; capital = " + capital + "; region = " + region + "; regionNbr = " + region_Nbr + "; population = " + capital_population;
}
}//end class
}//end class
Outputs...
[Country: name = Australia; capital = Canberra; region = AU; regionNbr = 61; population = 6000000]

Categories

Resources