I have a program that currently I'm trying to create a player with customizable integers. I use this object:
public class Player {
public String player = null;
private int Strength=0;
private int Defense=0;
private int Magic=0;
private int Resistance=0;
private int Skill=0;
private int Luck=0;
public Player(String name, int int1, int int2, int int3, int int4, int int5, int int6) {
this.player = name;
this.Strength = int1;
this.Defense = int2;
this.Magic = int3;
this.Resistance = int4;
this.Skill = int5;
this.Luck = int6;
}
}
I use this main class to run it, and set the integer and string values.
public class Main {
public static void main(String[] args) {
Player[] playerList = new Player[] {new Player("Player1", 3, 3, 2, 1, 1, 3),new Player("Player2", 1, 1, 1, 1, 1, 1)};
}
}
However, whenever I attempt to print this, it prints this:Player#659e0bfd
I looked through similar questions, but I am not sure where to put the #Override in my program, and if I need to do something different since I have multiple integers, and a string. I only want the string to print out. (Also, is there a way to print out just one part of the playerList, ie. the first section "Player1")
In the Player class you need to put the override.
Someting like:
public class Player {
// fields here
#Override
public String toString() {
return Strength + " " + Defense; // plus all the fields here
}
}
Regarding your other question: yes, you can, but since all the fields are private, you need to create getters for those fields. Then you can do:
public class Player {
private int defense;
private String name;
public Player(int defense, String name) {
this.defense = defense;
this.name = name;
}
public int getDefense() {
return this.defense;
}
public String getName() {
return this.name;
}
}
Player player = new Player(9000);
System.out.println(player.getName + " has defense + " player.getDefense());
Also, it's a good idea to stick to Java conventions. This means that variables are written with a lower case, like strength instead of Strength.
What you are seeing is the output of the toString method in the Object class, which your Player class implicitly extends. If you wish for it to output something else, you must override the toString() method in your Player class.
For instance, add something like this:
#Override
public String toString() {
return "Player(Strength: " + Strength + ", Defense: " + Defense + ")";
}
So basically i assume u use the System.out.println(); method to display ur Object right? You defined your own class and objects. You have to define your own print method, which you have to override. The method is called
#Override
public String toString(){ return this.Strength + " " + this....);
This method will be called automatically if you insert your object in your System.outprintln();
Related
I was using this code to print out the list of objects and i don't know if it was because i sorted them but it wont print correctly.
Collections.sort(cereal);
for (int i = 0; i<cereal.size(); i++){
System.out.println(cereal.get(i).toString());
}
I used this compare method for it and I'm not sure if it works either.
#Override
public int compareTo(Cereal o) {
return (int) (this.ratings - o.getRatings());
}
Thank you for the feedback.
Here is what is printing:
Unit3_7.Cereal#668bc3d5
Unit3_7.Cereal#3cda1055
Unit3_7.Cereal#7a5d012c
Unit3_7.Cereal#3fb6a447
Unit3_7.Cereal#79b4d0f
Unit3_7.Cereal#6b2fad11
This is a sample by the way and this is the object:
Cereal cereal1 = new Cereal(data[0], data[1],
Integer.parseInt(data[2]),
Integer.parseInt(data[3]),
Integer.parseInt(data[4]),
Integer.parseInt(data[5]),
Double.parseDouble(data[6]),
Double.parseDouble(data[7]),
Integer.parseInt(data[8]),
Integer.parseInt(data[9]),
Integer.parseInt(data[10]),
Integer.parseInt(data[11]),
Double.parseDouble(data[12]),
Double.parseDouble(data[13]),
Double.parseDouble(data[14]));
I'm getting the data from a csv file that I parsed also, I already confirmed it works and also here is the definition
public Cereal(String brandName, String type, int calories, int protein, int fat, int sodium, Double fiber, Double carbohydrates, int sugar, int potassium, int vitamins,int shelf,
Double weight, Double cups, Double ratings) {
this.brandName = brandName;
this.type = type;
this.calories = calories;
this.protein = protein;
this.fat = fat;
this.sodium = sodium;
this.fiber = fiber;
this.carbohydrates = carbohydrates;
this.sugar = sugar;
this.potassium = potassium;
this.vitamins = vitamins;
this.shelf = shelf;
this.weight = weight;
this.cups = cups;
this.ratings = ratings;
}
You need to provide your own implementation of toString(), e.g.
public String toString() {
return "Brand: " + this.brandName + ", type: " + this.type; // etc, etc
}
Object#toString()'s default implementation is used when you don't provide/inherit a different one for your class, which just gives you type and memory location info.
First of all, your comparator looks off, you probably want something like this instead:
#Override
public int compareTo(Cereal o) {
return ratings.compareTo(o.getRatings());
}
Then, make sure your Cereal class has a human-readable toString() implementation, eg.:
#Override
public String toString {
return String.format("Cereal: %s", this.getBrandName());
}
Ultimately you can print all Cereals in the list one by one as per your code, or you can print them out all at once like so:
Collections.sort(cereal);
System.out.println(cereal);
I am relatively new to programming and an working with setters and getters at the moment.
I have something set up where I have a student class that has information about said student, including their first, middle, and last name, their student ID, and their major.
I need to set it so that, if their student ID is less than zero, it automatically sets it to -1. I also need to set the major to undecided if they do not input anything.
I also need to override the toString method and print all of this information out.
I feel like I have the first part with the names down, I am not sure about the rest of it however. I am not sure how I am supposed to use the toString method while also using setters and getters.
Below is my Student class that does all of the work.
import java.util.Objects;
import java.util.Scanner;
public class Student {
String first;
String middle;
String last;
String major = "Undecided";
static int studentID = -1;
public Student(String first, String middle, String last) {
Objects.requireNonNull(first);
Objects.requireNonNull(last);
}
public void setFirst(String A) {
first = A;
}
public void setMiddle(String B) {
middle = B;
}
public void setLast(String C) {
last = C;
}
private String getFirst() {
return first;
}
private String getMiddle() {
return middle;
}
private String getLast() {
return last;
}
private String getMajor() {
return major;
}
public void setMajor(){
static void register(int a){
if (a < 0) {
studentID = a;
} else {
studentID = getID(a);
}
}
private static int getID(int a) {
if (studentIDInput < 0) {
studentID = -1;
} else {
studentID = a;
}
return studentID;
}
public static void main(String[] args) {
String first = "abc";
String middle = "def";
String last = "ghi";
Scanner sc = new Scanner(System.in);
String majorInput = sc.next();
int studentIDInput = sc.nextInt();
Student student1 = new Student(first, middle, last);
System.out.println(student1.getFirst().toString() + " " + student1.getMiddle().toString() + " " + student1.getLast().toString() + '\n' + "Major:" + " " + student1.getMajor().toString() + '\n' );
}
#Override
public String toString() {
return ;
}
}
I have also included the Driver class just for reference.
public class Driver {
static String first;
static String middle;
static String last;
public static void main(String[] args){
Student student1 = new Student(first, middle, last);
student1.setFirst("Mikayla");
student1.setMiddle("Rose");
student1.setLast("Knox");
}
}
You have this constructor:
public Student(String first, String middle, String last) {
Objects.requireNonNull(first);
Objects.requireNonNull(last);
}
It does its job of checking that first and last name are not null, but it does not do anything with the values besides checking. The constructor's job is to construct the object, i.e, initialize its member variables. When your constructor is done, you should have a usable object, without having to call any setters in it.
You need to add that:
public Student(String first, String middle, String last) {
Objects.requireNonNull(first);
Objects.requireNonNull(last);
this.first = first;
this.middle = middle;
this.last = last;
}
Note that you don't need to use setters here as code within the class can access member variables directly. You can use setters if you want, though.
As for toString: this is a method mainly used in debugging, and it displays some helpful information about the object it's called on. You could implement it like below, with a bit of ?: to make sure to only print the middle name if it's not null:
#Override
public String toString() {
return first + " " + (middle != null ? middle + " " : "") + last;
}
I'll leave it to you to also include major and ID.
On using a Scanner: You use a Scanner to get input from somewhere, like the from the user. You don't need it in toString or any setters or getters. These are all methods that should be very simple and not deal with I/O classes like Scanner.
If you are using constructors, you do not really need setters. Try something like this:
class Student {
private String first;
private String middle;
private String last;
private String major;
private int studentID;
public Student(String first, String middle, String last) {
this(first, middle, last, "undecided", -1);
}
public Student(String first, String middle, String last, String major, int studentID) {
this.first = first;
this.middle = middle;
this.last = last;
this.major = major;
this.studentID = studentID;
}
#Override
public String toString() {
return "first: " + first + "\nmiddle: " + middle + "\nlast: " + last + "\nmajor: " + major + "\nid: " _ studentID;
}
}
This way, when you create a new Student object with 3 parameters, the last 2 are automatically set to "undecided" and -1. If there is a case when you have the ID and not the major (or the other way around), you can add more constructors.
I seem to have a problem with a subtask. It's in danish so I put in the translated version of it:
Create a class Field, that is representing the fields of a monopoly game. Initially, Field can contain these encapsulated variables:
String name - short name of the field
int number - a number in the range[1..40]
Both variables must be initialized in a constructor, and there must only be getters, as they never will be changed after creation.
Moreover, there should be a method with the signature public String toString(), so it's easy to print what Field a player has landed on.
At first it's allowed to just call the fields Field1, Field2...
My Field class look like this:
public class Field {
String name;
int number;
public Field(String name, int number) {
this.name = name;
this.number = number;
}
public String getName() {
return name;
}
public int getNumber() {
return number;
}
}
In my main method I wanted to test this. So I wrote the following:
Field[] board = new Field[40]; // a board containing 40 fields
for (int i = 0; i < board.length; i++) {
board[i] = new Field("Field" + (i + 1), i + 1);
}
System.out.println("Board: " + Arrays.toString(board));
In my console I get this:
Board: [test.Field#2a139a55, test.Field#15db9742, test.Field#6d06d69c,......]
And I want this:
Board: [Field1, Field2, Field3,......]
Override Field's toString() to return the name, i.e.
public String toString() {
return name;
}
What you get (e.g. test.Field#2a139a55) is the default implementation of toString() which can be found in Object:
public String toString() {
return getClass().getName() + "#" + Integer.toHexString(hashCode());
}
You missed the
Moreover, there should be a method with the signatur public String toString(),
part of your task.
Are you able to use java8? Then I would suggest this:
Field[] board = new Field[40]; // a board containing 40 fields
for(int i = 0; i < board.length; i++){
board[i] = new Field("Field" + (i + 1), i + 1);
}
String commaSeparatedName =
Arrays.stream(board) // all items as stream
.map(Field::getName) // for each take its name
.collect(Collectors.joining(", "); // join names with a comma
System.out.println("Board: [" + commaSeparatedNames +"]");
String callsign;
String airlines[] = {"DLH","BER","TUI","EZY","ACA","AAL","FDX","SKW","ABY","SWR"};
public void assignCallsign()
{
Random r = new Random();
int airline = r.nextInt(10);
int number = r.nextInt(900) + 100;
callsign = airlines[airline] + number;
}
The String Array airlines[] contains 3 letters designating an airline.
The random integer airline is used to choose one of those airlines. The random integer number should designate the last 3 characters of an airplanes callsign.
I'm trying to get an output like "BER219", "AAL814" and so on, but upon executing the class, the String callsign is still null :/
Java passes variables by value. If you are testing the value of callsign variable outside this function then it will be null because you have set it to null outside of the assignCallsign method.
To remedy this, you can either:
return the callsign value from the function and set a variable with it.
public String assignCallSign() {
return airlines[airline] + number;
}
String callsign = assignCallSign()
make callsign a member variable of the class, and your code will function as you expect:
private String callsign;
It is difficult to see the issue without seeing the class that is using it.
Speculating this is part of some "Flight" object. This demonstrates the callsign being set and displayed correctly.
public static void main(String[] args) {
Flight flight = new Flight();
flight.assignCallsign();
System.out.println(flight);
}
private static class Flight {
private static final String AIRLINES[] = { "DLH", "BER", "TUI", "EZY", "ACA", "AAL", "FDX", "SKW", "ABY", "SWR" };
private String callsign;
public void assignCallsign() {
Random r = new Random();
int airline = r.nextInt(10);
int number = r.nextInt(900) + 100;
callsign = AIRLINES[airline] + number;
}
#Override
public String toString() {
return "Flight [callsign=" + callsign + "]";
}
}
Output
Flight [callsign=SKW534]
Okay, I don't know If I wrote a code correctly please check. So I created software for a store that sells one type of item. And each instance of my class should be an item of merchandise my store sells.
For example if my store sells neckties, I would design a necktie class:
class Necktie { …
My class must have five instance variables, including at least one of type integer, at least one of type String and one called price which must be double. Also it should have a toString method that accepts no parameters and returns a description of the item. It should have a constructor. The constructor can take however many parameters you choose, but it must set all instance variables.
• It should contain an accessor method for each instance variable.
• It should contain no unnecessary instance variables. Any information that does not need to be stored in an instance of your class should be stored as local variables.
Here is the code below. (incomplete, because I am kinda stuck..Please check if I did it correctly. If not, then please correct me.)
public class Pets {
public static void main(String[] args) {
System.out.print (Pets.toString()); //toString
}
String color, pattern;
int age, size;
double price;
Pets (String color, String pattern, int age, int size, double price){
this.color = color;
this.pattern = pattern;
age = age;
size = size;
price = price;
}
public String toString(){ //I don't get this part..
String description;
description = "red";
return description;
}
public String getColor(){
return color;
}
public String getPattern(){
return pattern;
}
public int age(){
return age;
}
public int size(){
return size;
}
public double price(){
return price;
}
}
Where you've written
age = age;
size = size;
price = price;
This is actually not setting the instance variable. You should carry on writing
this.age = age
// etc...
When you write this it tells Java that you're referring to the instance variable, not the local variable
When the main method is called, Java doesn't create an instance of Pets for you. But the rest of your code works on a Pets object, so you'll need to create one somewhere in your main. Thus, instead of:
public static void main(String[] args) {
System.out.print (Pets.toString()); //toString
}
it will be something like
public static void main(String[] args) {
Pets pet = new Pets(........); // creates an instance; you'll need to supply
// the arguments
System.out.print (pet.toString()); // calls toString on this instance
}
That will get past the "cannot make a static reference" error, but there are other problems as described in other answers.
Your main method tries to call a static method toString(), but your toString() method is not static (as it shouldn't be).
For testing purposes, your main method should look like this:
public static void main(String[] args) {
Pets pet = new Pets("red", "plain", 1, 2, 10.25);
System.out.println(pet.toString());
}
In your constructor:
Pets (String color, String pattern, int age, int size, double price){
this.color = color;
this.pattern = pattern;
this.age = age;
this.size = size;
this.price = price;
}
Your toString() method has a typo in the name. It should probably return a description of the attributes of the instance (not an actual description field). For example:
public String toString() {
StringBuilder description = new StringBuilder("Color: ")
.append(color)
.append(", Pattern: ")
.append(pattern)
.append(", Age: ")
.append(age)
.append(", Size: ")
.append(size)
.append(", Price: ")
.append(price);
return description.toString();
}
Your getters should start with get:
public int getAge(){
return age;
}
public int getSize(){
return size;
}
public double getPrice(){
return price;
}
Edit
At the OPs request:
An alternative toString() method which uses String concatenation (bad) and no special formatting:
public String toString() {
return "Color: " + color + ", Pattern: " + pattern + ", Age: " + age + ", Size: " + size + ", Price: " + price;
}