I am new to Java - I am trying to understand how to use a "derived" "attribute" in a class. My understanding is that this is basically the same as the typical "full name" use case using a getter in C#, but I want to make sure. In C#, I would write.
public string fullName
{
get {return this.fName + " " + this.lName;}
}
and then call it like this:
Dude homieG = new Dude()
{
fName = "Homie",
lName = "G"
};
Console.WriteLine(homieG.fullName);
https://dotnetfiddle.net/0ppd8j
How do I do this in Java? Googling "derived attribute (or 'property') java" gives me nothing.
Create a method. There are no "properties" in java.
public String getFullBlammy()
{
return firstName + " " + lastName;
}
Related
I have this example code that I want to pass some checkstyle rules but my formatter is not properly set up.
I just want an extra indent to lambda function body and change location of its right bracket }
This is what my code looks currently when I format it (Ctrl + Alt + L)
Optional.ofNullable(customerClient.
getActiveCustomers()).map(customer -> {
String firstName = customer.getFirstName();
String lastName = customer.getLastName();
return firstName + " " + lastName;
}).orElse(null);
but I need to change my formatter so that the code would look like this:
Optional.ofNullable(customerClient.
getActiveCustomers()).map(customer -> {
String firstName = customer.getFirstName();
String lastName = customer.getLastName();
return firstName + " " + lastName;
}
).orElse(null);
It's a known issue. Feel free to vote.
This question already has answers here:
How do I print my Java object without getting "SomeType#2f92e0f4"?
(13 answers)
Closed 6 years ago.
I have an array that I need to print, and I've already looked through stackoverflow so I know that I need to use toString so that I don't just print the hashcode, but for some reason it's still printing stuff like "music2.Music2#4162b8ce, music2.Music2#3852fdeb, music2.Music2#509c6c30"
Music2[] musiclist = new Music2[10];
musiclist[0] = new Music2("Pieces of You", "1994", "Jewel");
musiclist[1] = new Music2("Jagged Little Pill", "1995", "Alanis Morissette");
musiclist[2] = new Music2("What If It's You", "1995", "Reba McEntire");
musiclist[3] = new Music2("Misunderstood", "2001", "Pink");
musiclist[4] = new Music2("Laundry Service", "2001", "Shakira");
musiclist[5] = new Music2("Taking the Long Way", "2006", "Dixie Chicks");
musiclist[6] = new Music2("Under My Skin", "2004", "Avril Lavigne");
musiclist[7] = new Music2("Let Go", "2002", "Avril Lavigne");
musiclist[8] = new Music2("Let It Go", "2007", "Tim McGraw");
musiclist[9] = new Music2("White Flag", "2004", "Dido");
public static void printMusic(Music2[] musiclist) {
System.out.println(Arrays.toString(musiclist));
}
This is my array and the method that I am using to print it. Any help would be appreciated.
You should define toString() method in your Music2 class and print it in the way you like. I don't know how fields in your object are named exactly, but it can look like this:
public class Music2 {
...
#Override
public String toString() {
return this.artist + " - "+ this.title + " (" + this.year + ")";
}
}
After that your printMusic method will work as expected.
You can declare a for each loop to display the property of music. This is the code
for (Music2 music : musiclist){
System.out.println("Title: " + music.getTitle);
}
Because by default Arrays got toString() implementation of the Object class, that is:
public String toString() {
return getClass().getName() + "#" + Integer.toHexString(hashCode());
}
So you need to overwrite toString() in your Class
#Override
public String toString() {
return this.fieldNameone + " "+ this.fieldNametwo + " " + this.fieldNamethree + " ";
}
If using Java8 you can use
Arrays.stream(musiclist).forEach(System.out::print)
but make sure that Music2 has an overriden method for toString()
In the Arrays.toString(musiclist) you are actually invoking toString() on each element of the array to compose the resulting string. So, if you override the basic Object toString() implementation in Music2 class you will get what you want
public class Music2 {
.....
#Override
public String toString() {
return "Music2{" + "title=" + title + ", group=" + group + ", year=" + year + '}';
}
}
I'm trying to print the test data used in webdriver test inside a print line in Java
I need to print multiple variables used in a class inside a system.out.print function (printf/println/whatever).
public String firstname;
public String lastname;
firstname = "First " + genData.generateRandomAlphaNumeric(10);
driver.findElement(By.id("firstname")).sendKeys(firstname);
lastname = "Last " + genData.generateRandomAlphaNumeric(10);
driver.findElement(By.id("lastname")).sendKeys(lastname);
I need those print in a print statement as:
First name: (the variable value I used)
Last name: (the variable value I used)
Using something like below gives the exact result.
But I need to reduce the number of printf lines and use a more efficient way.
System.out.printf("First Name: ", firstname);
System.out.printf("Last Name: ", lastname);
Thanks!
You can do it with 1 printf:
System.out.printf("First Name: %s\nLast Name: %s",firstname, lastname);
Or try this one:
System.out.println("First Name: " + firstname + " Last Name: "+ lastname +".");
Good luck!
System.out.println("First Name: " + firstname);
System.out.println("Last Name: " + lastname);
or
System.out.println(String.format("First Name: %s", firstname));
System.out.println(String.format("Last Name: %s", lastname));
You can create Class Person with fields firstName and lastName and define method toString(). Here I created a util method which returns String presentation of a Person object.
This is a sample
Main
public class Main {
public static void main(String[] args) {
Person person = generatePerson();
String personStr = personToString(person);
System.out.println(personStr);
}
private static Person generatePerson() {
String firstName = "firstName";//generateFirstName();
String lastName = "lastName";//generateLastName;
return new Person(firstName, lastName);
}
/*
You can even put this method into a separate util class.
*/
private static String personToString(Person person) {
return person.getFirstName() + "\n" + person.getLastName();
}
}
Person
public class Person {
private String firstName;
private String lastName;
//getters, setters, constructors.
}
I prefer a separate util method to toString(), because toString() is used for debug.
https://stackoverflow.com/a/3615741/4587961
I had experience writing programs with many outputs: HTML UI, excel or txt file, console. They may need different object presentation, so I created a util class which builds a String depending on the output.
Suppose we have variable date , month and year then we can write it in the java like this.
int date=15,month=4,year=2016;
System.out.println(date+ "/"+month+"/"+year);
output of this will be like below:
15/4/2016
I'm writing something similar to smarterChild (that automated AOL Instant Messenger chat program from back in the day) and was curious about my method of determining sentence structure and response.
Currently, the bare bones design is to use 5 main methods which collectively determine the appropriate response given the user input:
1) Read(): initially accepts user input, then calls first of many methods: sentenceType()
2) getSentenceType(): User sentence type: Question, statement, directive, suggestion, etc…
3) getWho(): If question is about the computer, or about someone else…
4) getCategory(): What category the question is about (weather, sports…)
5) getResponse(): finally, form a response
These methods will query a database to determine if the user input contains key words...
Example of getSentenceType():
public String getSentenceType(String sentence) {
String type = null;
for (String s : db.getQuestions()) {
if (sentence.contains(s)) {
type = "question";
break;
}
else {
type = "statement";
}
}
return getWho(type, sentence);
}
Example of the final method which returns sentence structure:
//final call...
public String getResponse(String cat, String who, String type) {
String response = new String();
String auxVerb, subject, mainVerb, noun;
auxVerb = "do";
subject = who;
mainVerb = "like";
noun = cat;
//question structure: auxiliary verb + subject + main verb + noun/pronoun
// DO YOU LIKE MARY?
if (type.equals("question")) {
response = subject + " " + auxVerb + " " + mainVerb + " " + noun + ". ";
}
else {
response = auxVerb + " " + subject + " " + mainVerb + " " + noun + "?";
}
return response;
}
Sample database methods:
public String[] getQuestions() {
String[] questions = new String[] {"why", "?"};
return questions;
}
public String[] getWeather() {
String[] weather = new String[] {"cold", "hot", "rainy", "weather"};
return weather;
}
It will then progressively concatenate all the method results into a coherent response… then send that result back to Read(), which will print out the result to the user...
Is this an inefficient way to go about this? I know that if I continue down this path... to make a robust system, it will take tons of if else checks and a massive database to determine every possible type of response for user input.
Are there any suggested methods?
Thank you
I am adding information from main()
I am adding different information for CD, DVD, book..
I have 3 separate classes - item has 3 classes in it...
project - main()
Library - this function does all the adding
Item(cd,dvd,book) inheritance
For Music i am adding band info, title info, keywords, and members..
I am adding members separately than of the other info..
As you can see the members is not outputing correctly as the others..
>>> music CDs:
-Music-
band: Jerry Garcia Band
# songs: 15
members: [Ljava.lang.String;#61de33
title: Don't Let Go
C:\Java\a03>
I am using the same toString() function for members as i am the rest, so i am not sure why it would do this..
I will give you as much info as i think you need to see..
Main() - as you can see it calls 2 different functions.
the addbandmembers is where i am having problems...
out.println(">>> adding items to library:\n");
item = library.addMusicCD("Europe In '72", "Grateful Dead", 12, "acid rock", "sixties", "jam bands");
if (item != null) {
library.addBandMembers(item, "Jerry Garcia", "Bill Kreutzman", "Keith Godcheaux");
library.printItem(out, item);
}
in Library class - here is the addbandmember function ..
Could this be the cause??
public void addBandMembers(Item musicCD, String... members)
{
((CD)musicCD).addband(members);
}
In the Items class here is the function addband - tostring()
here is the CD class which extends the items class..
class Item
{
private String title;
public String toString()
{
String line1 = "title: " + title + "\n";
return line1;
}
public void print()
{
System.out.println(toString());
}
public Item()
{}
public Item(String theTitle)
{
title = theTitle;
}
public String getTitle()
{
return title;
}
}
class CD extends Item
{
private String artist;
private String [] members;
private int number;
public CD(String theTitle, String theBand, int Snumber, String... keywords)
{
super(theTitle);
this.artist = theBand;
this.number = Snumber;
}
public void addband(String... member)
{
this.members = member;
}
public String getArtist()
{
return artist;
}
public String [] getMembers()
{
return members;
}
public String toString()
{
return "-Music-" + "\n" + "band: " + artist + "\n" + "# songs: " + number + "\n" + "members: " + members + "\n" + "\n" + super.toString() + "\n";
}
public void print()
{
System.out.println(toString());
}
}
I do have other information in the items class like a nook class, movie class that i didnt show. I would like to keep everything the way i have it set up..
So, if the other items are printing fine than maybe its the cast in the addbandmember function thats giving me problems?
members is printing the way it is since it's an array (you can tell this by the fact its output as members: [Ljava.lang.String;#61de33 ).
Instead you need to iterate through it and print each element.
e.g.
for (String member : members) {
...
}
The simplest way is to use Arrays.toString(). Alternatively append to a StringBuilder and then print to this. You can be cleverer, and use StringUtils.join() from Apache Commons Lang, which will give you more control.
Arrays don't have a useful toString() implementation. You can print out the members in a loop or use the Arrays.toString() method to do this for you:
return "-Music-" + "\n"
+ "band: " + artist + "\n"
+ "# songs: " + number + "\n"
+ "members: " + Arrays.toString(members) + "\n"
+ "\n"
+ super.toString() + "\n";