I got 2 classes
class Curso{
private String name;
public Curso(String nome){
this.name = nome;
}
public String getName(){
return this.name;
}
}
and
public class testaCurso{
public static void main(String[] args){
Course c1 = new Course("Computer Science");
c1.addDisciplina("AlgProgII");
c1.addDisciplina("SO");
c1.addDisciplina ("Grafos");
System.out.println(c1);
}
}
i gotta modify the Course class so that it can store the names of the Disciplina that make up the course and work for the test above with the output as shown. Consider that a course will not have a maximum of 50 subjects.
output:
Course: Computer Science,
Disciplinas:{ AlgProgII SO Grafos }
class Curso {
private String name;
// Add an list field containg the disciplinas
private final List<String> disciplinas = new ArrayList<>();
public Curso(String name){
this.name = name;
}
public String getName(){
return this.name;
}
// Add a `addDisciplina` method
public void addDisciplina(String name) {
disciplinas.add(name);
}
// Override the `toString` method
#Override
public String toString() {
return "Course: " + name + ", Disciplinas: + ", disciplinas;
}
}
We can implement toString() like the following:
public class Course {
private final String name;
private final List<String> disciplinas;
public Course(String name){
this.name = name;
this.disciplinas = new ArrayList<>();
}
public Course(String name, List<String> disciplinas){
this.name = name;
this.disciplinas = new ArrayList<>(disciplinas);
}
public void addDisciplinas(String discplina){
this.disciplinas.add(discplina);
}
#Override
public String toString() {
return "Course: " + name + ", Disciplinas: {" + disciplinas.stream().collect(Collectors.joining(" ")) +"}";
}
}
Usage:
Course course = new Course("Computer Science", Arrays.asList("AlgProgII", "SO", "Grafos"));
System.out.println(course);
Output:
Course: Computer Science, Disciplinas: {AlgProgII SO Grafos}
Related
I'm new in Java :] and I have a little problem with my app:
Why when I run it, it keeps saying me "null" even when person.setname("John")
I tried to fix it but without good result, what is wrong here and why?
I tried to debug it - same result - setName set name to John but anyway it keeps printing "null"
Really strange for new user like me.
If someone can help, or even try to say me what's wrong i'd be glad, thanks.
class App {
public static void main(String[] args) throws InterruptedException {
List<String> blacklist = Arrays.asList("Bill, Adam, Jessie");
;
Person person = new PersonWithBlacklistedCheck(
new PersonWithNullCheck(new Person()),
blacklist);
person.setName("John");
System.out.println("Person: " + person);
}
}
class PersonWithBlacklistedCheck extends Person {
private final List<String> blacklist;
private final Person target;
PersonWithBlacklistedCheck(Person target, List<String> blacklist) {
this.target = target;
this.blacklist = blacklist;
}
#Override
public String getName() {
return target.getName();
}
#Override
public void setName(String name) {
if (this.blacklist.contains(name)) {
throw new RuntimeException("[" + name + "] cannot be used as a name! it is blacklisted");
}
target.setName(name);
}
}
class Person {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
#Override
public String toString() {
return "Person{" +
"name='" + name + '\'' +
'}';
}
}
class PersonWithNullCheck extends Person {
private final Person target;
PersonWithNullCheck(Person target) {
this.target = target;
}
#Override
public String getName() {
return target.getName();
}
#Override
public void setName(String name) {
if (name == null) {
throw new RuntimeException("[name] must not be null!!");
}
target.setName(name);
}
}
You have person object containing another person called "target" and another one "target" :
Blacklist should look like this:
List<String> blacklist = Arrays.asList("Bill", "Adam", "Jessie");
You were creating one entry: "Bill, Adam, Jessie".
You were doing some unnecessary metods override, adding unnecessary objects - when you extend class you have that object "person" already there, you don't need to put it as another object "target". If you want to have both null check and blacklist check executed before setting name you can extend classes in hierarchy: Person -> PersonWithNullCheck -> PersonWithBlacklistedCheck. Now setName() method will be executed in each of classes as ordered. Here's a fixed solution:
public class Test {
public static void main(String[] args) {
List<String> blacklist = Arrays.asList("Bill", "Adam", "Jessie");
Person person = new PersonWithBlacklistedCheck(blacklist);
person.setName("John");
System.out.println("Person: " + person);
}
}
class PersonWithBlacklistedCheck extends PersonWithNullCheck {
private final List<String> blacklist;
PersonWithBlacklistedCheck(List<String> blacklist) {
this.blacklist = blacklist;
}
#Override
public void setName(String name) {
if (this.blacklist.contains(name)) {
throw new RuntimeException("[" + name + "] cannot be used as a name! it is blacklisted");
}
super.setName(name);
}
}
class PersonWithNullCheck extends Person {
#Override
public void setName(String name) {
if (name == null) {
throw new RuntimeException("[name] must not be null!!");
}
super.setName(name);
}
}
class Person {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
#Override
public String toString() {
return "Person{" +
"name='" + name + '\'' +
'}';
}
}
This question already has answers here:
How do I print my Java object without getting "SomeType#2f92e0f4"?
(13 answers)
Closed 4 years ago.
i want to print all elements of my array list. Eclipse does not show an error, but it doesnt show the elements that i added in console. Can you please tell me what i did wrong?
The console shows:
Typ:Droide
ID:8282
NameR2D2
HumanoiderRoboter#15db9742
HumanoiderRoboter#6d06d69c
HumanoiderRoboter#7852e922
HumanoiderRoboter#4e25154f
Roboter Class:
public class Roboter {
protected String Name;
protected int ID;
protected String typ;
public Roboter(String Name, int ID, String typ) {
super();
this.Name = Name;
this.ID = ID;
this.typ = typ;
}
public void ausgebenNeu() {
System.out.println("ID:"+ID);
System.out.println("Name:"+Name);
System.out.println("Typ:"+typ);
}
HumanoiderRoboter Class:
import java.util.ArrayList;
public class HumanoiderRoboter extends Roboter {
String RoboterTyp;
public HumanoiderRoboter (String Name, int ID, String typ) {
super(Name, ID, typ);
}
public void ausgeben() {
ArrayList<HumanoiderRoboter> Sensoren = new ArrayList<HumanoiderRoboter>();
Sensoren.add(new HumanoiderRoboter("Sensor1", 4232, "Infrarotsensor"));
Sensoren.add(new HumanoiderRoboter("Sensor2", 9232, "Lichtsensor"));
Sensoren.add(new HumanoiderRoboter("Sensor3", 5777, "Touchssensor"));
Sensoren.add(new HumanoiderRoboter("Sensor4", 3321, "Gyrosensor"));
System.out.println("Typ:" + typ);
System.out.println("ID:" + ID);
System.out.println("Name" + Name);
for (Roboter ele : Sensoren) {
System.out.println(ele);
}
}
public static void main(String[] args) {
HumanoiderRoboter R2 = new HumanoiderRoboter("R2D2", 8282, "Droide");
R2.ausgeben();
}
}
Currently your problem is the HumanoiderRoboter doesn't overwrite the toString method which results the HumanoiderRoboter#4e25154f stuff. So if you overwrite the toString method it will print your object stuff you put in there:
...
#Override
public String toString() {
return "Typ: " + type + ", ID: " + id + ", Name: " + name;
}
...
Default toString method from Object looks like that:
public String toString() {
return getClass().getName() + "#" + Integer.toHexString(hashCode());
}
So now if you do System.out.println(theObject) it will for example result something like this:
Typ: some, ID: 5, Name: NiceRoboter
And if you want the complete array as one String you can use the Arrays#toString method:
System.out.println(Arrays.toString(yourList.toArray()));
In your Roboter class override toString() method like this:
public class Roboter {
//-----member fields,methods
//Add this method
#Override
public String toString(){
return "{name:"+this.Name+"}";
}
}
Also read this link for naming convention to follow in Java https://www.geeksforgeeks.org/java-naming-conventions/
Override toString() method in Roboter class.
public class Test extends Roboter {
String RoboterTyp;
public Test(String Name, int ID, String typ) {
super(Name, ID, typ);
}
public void ausgeben() {
ArrayList<Test> Sensoren = new ArrayList<Test>();
Sensoren.add(new Test("Sensor1", 4232, "Infrarotsensor"));
Sensoren.add(new Test("Sensor2", 9232, "Lichtsensor"));
Sensoren.add(new Test("Sensor3", 5777, "Touchssensor"));
Sensoren.add(new Test("Sensor4", 3321, "Gyrosensor"));
System.out.println("Typ:" + typ);
System.out.println("ID:" + ID);
System.out.println("Name" + Name);
for (Roboter ele : Sensoren) {
System.out.println(ele);
}
}
public static void main(String[] args) {
Test R2 = new Test("R2D2", 8282, "Droide");
R2.ausgeben();
}
}
public class Roboter {
String Name;
int ID;
String typ;
public Roboter(String name, int iD, String typ) {
super();
Name = name;
ID = iD;
this.typ = typ;
}
public String getName() {
return Name;
}
public void setName(String name) {
Name = name;
}
public int getID() {
return ID;
}
public void setID(int iD) {
ID = iD;
}
public String getTyp() {
return typ;
}
public void setTyp(String typ) {
this.typ = typ;
}
#Override
public String toString() {
return "Roboter [Name=" + Name + ", ID=" + ID + ", typ=" + typ + "]";
}
}
I have an assignment to make a Country class with two fields(name, capital) which at first has to be compared with another Country based on the name. Afterwards without changing anything I have to make another test which cares only about the capital regarding comparison. How to do two different comparison methods in the same class ?
This is what I've done so far :
Country class :
public class Country implements Comparable {
private String name;
private String capital;
public Country(String name, String capital) {
this.name = name;
this.capital = capital;
}
public String getName() {
return name;
}
public String getCapital() {
return capital;
}
#Override
public String toString() {
return "Country{" +
"name='" + name + '\'' +
", capital='" + capital + '\'' +
'}';
}
public static final Comparator<Country> nameComparator = (country, secondCountry) -> country.getName().compareTo(secondCountry.getName());
public static final Comparator<Country> capitalComparator = (country, secondCountry) -> country.getCapital().compareTo(secondCountry.getCapital());
#Override
public int compareTo(Object o) {
return 0;
}
}
Method which checks if countries are sorted correctly:
public boolean isSorted(List<Country> countryList) {
boolean sorted = Ordering.natural().isOrdered(countryList);
return sorted;
}
And my test:
#org.junit.Test
public void testIfTheListIsSorted () {
CountryDAO countryDAO = new CountryDAO();
List<Country> countryList = countryDAO.getCountryList();
Collections.sort(countryList, Country.nameComparator);
assertTrue(countryDAO.isSorted(countryList));
}
What do I have to change in order to compare at my choice , whether by name or by capital ? And both ways being testable. Thanks in advance..
So it seems like I have to make an object array of a sub-class (Bicycle).
I then add two objects to this.. and loop the array and print what each object is constructed from.
This sounds thoroughly confusing to me, and I'm unsure how to go about this.
I'll also post the rest of my code, to make more sense.
MAIN:
package javaapplication4;
public class JavaApplication4 {
public static void main(String[] args) {
Bicycle myBike = new Bicycle(1, "Haro BMX", true, "Handlebars, Tyres, Frame");
System.out.println(myBike);
}
}
package javaapplication4;
public class Implement {
String name;
boolean hasMovingParts;
String constructedFrom;
public Implement() {
}
public Implement(String name, boolean hasMovingParts, String constructedFrom) {
this.name = name;
this.hasMovingParts = hasMovingParts;
this.constructedFrom= constructedFrom;
}
public String getName() {
return name;
}
public boolean getMovingParts() {
return hasMovingParts;
}
public String getConstructedFrom(){
return constructedFrom;
}
public class Bicycle extends Implement {
public int seatNumber;
public Bicycle(int seatNumber, String name, boolean hasMovingParts, String constructedFrom) {
this.seatNumber = seatNumber; //takes the value you pass as parameter
this.name = name; // and stores it into the instance variable
this.hasMovingParts = hasMovingParts;
this.constructedFrom = constructedFrom;
}
#Override
public String toString(){
return String.format("*Vehicle Statistics* Seats: %d, Name:" +
" %s, Contains Moving Parts: %b, Materials: %s",
seatNumber, name, hasMovingParts, constructedFrom);
}
}
}
package javaapplication4;
public class Bicycle extends Implement {
public int seatNumber;
public Bicycle(int seatNumber, String name, boolean hasMovingParts, String constructedFrom) {
this.seatNumber = seatNumber;
this.name = name;
this.hasMovingParts = hasMovingParts;
this.constructedFrom = constructedFrom;
}
#Override
public String toString() {
return String.format("*Vehicle Statistics* Seats: %d, Name:" +
" %s, Contains Moving Parts: %b, Materials: %s",
seatNumber, name, hasMovingParts, constructedFrom);
}
}
Change your main method to create an array of Bicycles, then add them by the index :
public static void main(String[] args) {
Bicycle[] bicycles = new Bicycle[2];
bicycles[0] = new Bicycle(1, "Haro BMX", true, "Handlebars, Tyres, Frame");
bicycles[1] = new Bicycle(1, "Orah XMB", true, "Handlebars, Tyres, Frame");
for (Bicycle bicycle : bicycles){
System.out.println(bicycle);
}
}
What would be the simplest method to print this array broken down into each mobile phone as a product number, name department etc, and then re print the same information sorted by product name. I have tried a couple different methods and am already passed the turn in date for the assignment but still need to figure it out for upcoming assignment this weekend. When I try to implement the comparator on MobilePhone class it forces me to make it abstract or use #override but I can't figure out where or what to override to make it work because the abstract class causes a multitude of other problems.
package InventoryPro2;
import java.util.*;
class MobilePhone {
private double productNumber; // Variables
private String name;
private String department;
private double unitsInStock;
private double unitPrice;
public MobilePhone() {
this(0.0, "", "", 0.0, 0.0);
}
public MobilePhone(double productNumber, String name, String department,
double unitsInStock, double unitPrice) { //assign variables
this.productNumber = productNumber;
this.name = name;
this.department = department;
this.unitsInStock = unitsInStock;
this.unitPrice = unitPrice;
}
public double getproductNumber() { // retrieve values
return productNumber;
}
public String getname() {
return name;
}
public String getdepartment() {
return department;
}
public double getunitPrice() {
return unitPrice;
}
public double getunitsInStock() {
return unitsInStock;
}
public void setproductNumber(double productNumber) {
this.productNumber = productNumber;
}
public void setname(String name) {
this.name = name;
}
public void setdepartment(String department) {
this.department = department;
}
public void setunitPrice(double unitPrice) {
this.unitPrice = unitPrice;
}
public void setunitsInStock(double unitsInStock) {
this.unitsInStock = unitsInStock;
}
public double gettotalInv() {
return getunitPrice() * getunitsInStock();
}
}
public class InventoryPro2 {
MobilePhone mobilephone = new MobilePhone();
public static void main(String args[]) {
System.out.println("Mobile Phone Inventory Program");
System.out.println();//skips a line
MobilePhone[] phones = new MobilePhone[5];
phones[0] = new MobilePhone();
phones[0].setproductNumber(1);
phones[0].setname("Motorola");
phones[0].setdepartment("Electronics");
phones[0].setunitPrice(150.10);
phones[0].setunitsInStock(98);
phones[1] = new MobilePhone();
phones[1].setproductNumber(2);
phones[1].setname("Samsung");
phones[1].setdepartment("Electronics");
phones[1].setunitPrice(199.99);
phones[1].setunitsInStock(650);
phones[2] = new MobilePhone();
phones[2].setproductNumber(3);
phones[2].setname("Nokia");
phones[2].setdepartment("Electronics");
phones[2].setunitPrice(200.25);
phones[2].setunitsInStock(125);
phones[3] = new MobilePhone();
phones[3].setproductNumber(4);
phones[3].setname("LG");
phones[3].setdepartment("Electronics");
phones[3].setunitPrice(100.05);
phones[3].setunitsInStock(200);
phones[4] = new MobilePhone();
phones[4].setproductNumber(5);
phones[4].setname("IPhone");
phones[4].setdepartment("Electronics");
phones[4].setunitPrice(299.99);
phones[4].setunitsInStock(150);
System.out.println("Order of inventory before sorting:");
System.out.println();
}
}
(Also, what is the best way to take just one piece of information out of each part of the array such as the totalInv and total all of those numbers to print?) Do I have unnecessary code here or have I done everything right thus far? I have to say that learning this coding language in an online format has not been a very enjoyable experience thus far..
Here is how to sort by name
import java.util.Arrays;
import java.util.Comparator;
public class AppInventoryPro2 {
public static void main(String... args) {
System.out.println("Mobile Phone Inventory Program");
System.out.println();// skips a line
MobilePhone[] phones = new MobilePhone[5];
phones[0] = new MobilePhone();
phones[0].setproductNumber(1);
phones[0].setname("Motorola");
phones[0].setdepartment("Electronics");
phones[0].setunitPrice(150.10);
phones[0].setunitsInStock(98);
phones[1] = new MobilePhone();
phones[1].setproductNumber(2);
phones[1].setname("Samsung");
phones[1].setdepartment("Electronics");
phones[1].setunitPrice(199.99);
phones[1].setunitsInStock(650);
phones[2] = new MobilePhone();
phones[2].setproductNumber(3);
phones[2].setname("Nokia");
phones[2].setdepartment("Electronics");
phones[2].setunitPrice(200.25);
phones[2].setunitsInStock(125);
phones[3] = new MobilePhone();
phones[3].setproductNumber(4);
phones[3].setname("LG");
phones[3].setdepartment("Electronics");
phones[3].setunitPrice(100.05);
phones[3].setunitsInStock(200);
phones[4] = new MobilePhone();
phones[4].setproductNumber(5);
phones[4].setname("IPhone");
phones[4].setdepartment("Electronics");
phones[4].setunitPrice(299.99);
phones[4].setunitsInStock(150);
System.out.println("Order of inventory before sorting:");
System.out.println(Arrays.toString(phones));
Arrays.sort(phones, new Comparator<MobilePhone>() {
#Override
public int compare(MobilePhone mp1, MobilePhone mp2) {
return mp1.getname().compareTo(mp2.getname());
}
});
System.out.println("Order of inventory after sorting by name:");
System.out.println(Arrays.toString(phones));
}
}
class MobilePhone {
private double productNumber; // Variables
private String name;
private String department;
private double unitsInStock;
private double unitPrice;
public MobilePhone() {
this(0.0, "", "", 0.0, 0.0);
}
public MobilePhone(double productNumber, String name, String department,
double unitsInStock, double unitPrice) { // assign variables
this.productNumber = productNumber;
this.name = name;
this.department = department;
this.unitsInStock = unitsInStock;
this.unitPrice = unitPrice;
}
public double getproductNumber() { // retrieve values
return productNumber;
}
public String getname() {
return name;
}
public String getdepartment() {
return department;
}
public double getunitPrice() {
return unitPrice;
}
public double getunitsInStock() {
return unitsInStock;
}
public void setproductNumber(double productNumber) {
this.productNumber = productNumber;
}
public void setname(String name) {
this.name = name;
}
public void setdepartment(String department) {
this.department = department;
}
public void setunitPrice(double unitPrice) {
this.unitPrice = unitPrice;
}
public void setunitsInStock(double unitsInStock) {
this.unitsInStock = unitsInStock;
}
public double gettotalInv() {
return getunitPrice() * getunitsInStock();
}
#Override
public String toString() {
return "MobilePhone [productNumber=" + productNumber + ", name=" + name
+ ", department=" + department + ", unitsInStock="
+ unitsInStock + ", unitPrice=" + unitPrice + "]";
}
}
1 - To print content of MobilePhone class: Override default toString method like this:
#Override
public String toString() {
return "MobilePhone [productNumber=" + productNumber +
", name=" + name + ']'; // add more info if needed
}
2 - To allow sorting by name: Have MobilePhone class implement Comparable interface like
this:
class MobilePhone implements Comparable {
...
#Override
public int compareTo(Object o) {
MobilePhone m = (MobilePhone) o;
return (this.name.compareTo(o.name));
}
}
EDIT: To print your array of MobilePhone object you can do:
System.out.printf("Phones: %s%n", Arrays.toString(phones));