I am trying to print each part of my noteArray (eg: 19, and then "D" as separate parts) But by using a For loop I get an a mumble up print message for each line. The "processNotes(noteArray)" method is how I want my output to look.
Any help would be much appreciated!
public class question2 {
public static void main(String[] args) {
Note[] noteArray = new Note[5];
noteArray[0] = new Note(19, "D");
noteArray[1] = new Note(10, "C");
noteArray[2] = new Note(23, "F");
noteArray[3] = new Note(20, "B");
noteArray[4] = new Note(32, "C");
processNotes(noteArray);
for(Note i : noteArray){
System.out.println(i);
}
}
private static void playNote() {
int numberDuration = Note.getduration();
String letterPitch = Note.getpitch();
System.out.println("The note "+ letterPitch +" is played for "+
numberDuration +" seconds.");
return;
}
public static void processNotes(Note[] notes) {
playNote();
}
}
class Note
{
private static String pitch;
private static int duration;
public Note(int duration, String pitch) {
this.pitch = "C";
this.duration = 10;
}
public static int getduration() {
return duration;
}
public void setduration(int duration) {
Note.duration = duration;
}
public static String getpitch() {
return pitch;
}
public void setpitch(String pitch) {
Note.pitch = pitch;
}
}
EDIT:
Output I would like:
The note C is played for 10 seconds.
Output of arrays I get:
Note#6d06d69c
Note#7852e922
Note#4e25154f
Note#70dea4e
Note#5c647e05
You have two possibility.
First, override your toString() method so that it prints your notes as you want when you System.out.println().
Second, you can in your loop, instead of printing the note :
for(Note i : noteArray){
System.out.println(i.getPitch());
System.out.println(i.getDuration());
}
Add the following to your Note class:
public String toString() {
return "Duration = " + duration + ", pitch = " + pitch;
}
Demo
From object.toString:
Returns a string representation of the object. In general, the
toString method returns a string that "textually represents" this
object. The result should be a concise but informative representation
that is easy for a person to read. It is recommended that all
subclasses override this method.
The toString method for class Object returns a string consisting of
the name of the class of which the object is an instance, the at-sign
character `#', and the unsigned hexadecimal representation of the hash
code of the object. In other words, this method returns a string equal
to the value of:
getClass().getName() + '#' + Integer.toHexString(hashCode())
You can override this method for a more meaningful output.
Suggested further read: The connection between 'System.out.println()' and 'toString()' in Java
You can just override toString method of the Note class, as sysout implicitly call toString.
Related
This question already has answers here:
How do I print my Java object without getting "SomeType#2f92e0f4"?
(13 answers)
Closed 2 years ago.
My output is currently:
Avengers#15db9742 Avengers#6d06d69c
I need to figure out how to display the names as well, using the generic print method. I've been trying things like: GenericMethod_violette.<Avengers>print(avenger.getName()) and GenericMethod_violette.<Avengers>print(avenger.trueIdentity()) but after days on this I seem to be stuck.
My output needs to be:
Avengers#15db9742 Avengers#6d06d69c
Tony Stark, Bruce Banner
My GenericMethod_violette.java:
import java.io.ObjectInputStream.GetField;
public class GenericMethod_violette {
public static void main(String[] args ) {
Avengers[] avenger = { new Avengers("Tony Stark"), new Avengers("Bruce Banner")};
GenericMethod_violette.<Integer>print(integers);
GenericMethod_violette.<String>print(strings);
GenericMethod_violette.<Avengers>print(avenger);
}
public static <E> void print(E[] list) {
for (int i = 0; i < list.length; i++)
System.out.print(list[i] + " ");
System.out.println();
}
}
My Avengers.java:
public class Avengers
{
private String trueIdentity;
public Avengers(String name)
{
trueIdentity = name;
}
public String getName()
{
return trueIdentity;
}
public String sayTrueIdentity()
{
return "Hello, I'm " + trueIdentity + "!";
}
}
you can use write toString inside Avengers
public class Avengers
{
private String trueIdentity;
public Avengers(String name)
{
trueIdentity = name;
}
public String getName()
{
return trueIdentity;
}
public String sayTrueIdentity()
{
return "Hello, I'm " + trueIdentity + "!";
}
// write any format you want to print
#override
public String toString()
{
return this.getName() + this.sayTrueIdentity();
}
}
then change your GenericMethod_violette.print method to use toString()
public static <E> void print(E[] list) {
for (int i = 0; i < list.length; i++)
System.out.print(list[i] + " ");
System.out.println();
}
Reason for Avengers print format - Avengers#15db9742
In java all objects have a toString() method, which is invoked when you try and print the object.
System.out.println(myObject); // invokes myObject.toString()
This method is defined in the Object class (the superclass of all Java objects). The Object.toString() method returns a fairly ugly looking string, composed of the name of the class, an # symbol and the hashcode of the object in hexadecimal. The code for this looks like:
// Code of Object.toString()
public String toString() {
return getClass().getName() + "#" + Integer.toHexString(hashCode());
}
So you need #overrride toString method.
Your print result of Avengers#15db9742 would mean that it is an object that you printed. If you want to print something meaningful, you need to override the toString() method of said object. In this case, of your Avengers object.
public String toString(){
return trueIdentity;
}
Added notes from #markspace of java toString().
The class Avengers doesn't override the Object::toString method which System.out.println implicitely uses in its implementation. I suggest you to read more at: How to override toString() properly in Java?.
However, this solution requires all the possible objects passed into the method to override such method, which you cannot guarantee. I recommend you to pass a Function<E, String> that exctracts from the generic type the field(s) as String to be printed out:
public static <E> void print(E[] array, Function<E, String> extractor) {
for (E e: array) {
System.out.print(extractor.apply(e) + " ");
}
System.out.println();
}
The usage is fairly simple (the generic type can be omitted as long as it is inferred):
// both following lines are basically identical
GenericMethod_violette.print(avenger, a -> a.getName());
GenericMethod_violette.print(avenger, Avenger::getName);
// if Avengers have more of the fields or they are to be customized, ex.:
GenericMethod_violette.print(avenger, a -> "Mr." + a.getName().toUpperCase());
Disclaimer: This solution requires Java 8. If you use Java 7 or lower, you are stick to override the Object::toString in all the expected classes:
#Override
public String toString() {
return this.getName();
}
This question already has answers here:
How to use the toString method in Java?
(13 answers)
Closed 3 years ago.
I've got two classes, below. When I run the class TestSimple, it prints out "blueblueblue is blue repeated". That print statement is executed as System.out.println(item) which is an instance of the Simple() class. I've never seen an object print out as a phrase before, and I'm having a hard time pinning down why this is happening.
I see that there is a method in the Simple class called toString which should print this out when it is called, but I don't see that method called anywhere. What's going on here?
public class Simple {
private String word;
private String phrase;
public Simple(int number, String w) {
word = w;
phrase = mystery(number, w);
}
private String mystery(int num, String s) {
String answer = "";
for (int k=0; k<num; k++) {
answer = answer + s;
}
return answer;
}
public String toString() {
return phrase + " is " + word + " repeated";
}
}
And
public class TestSimple{
public void print() {
Simple item = new Simple(3, "blue");
System.out.println(item);
}
public static void main(String[] args) {
new TestSimple().print();
}
}
System.out is a PrintStream, PrintStream.println(Object) (from the linked Javadoc) calls at first String.valueOf(x) to get the printed object's string value and String.valueOf(Object) returns the value of obj.toString()
How would I create a method that has the input of a string and output of all the strings that were input into it like a super string?
for example in the main class:
a= "fido"
b= "rufus"
c= "dog"
superString(a);
superString(b);
superString(c);
System.out.println(superString()); should be "fidorufusdog"
so far I have=
public static String superString (String sb) {
StringBuilder ssb = new StringBuilder(32);
ssb = ssb.append(sb);
return ssb.toString();
}
My code below is what I am working on for a stock simulator:
public class Operators {
public static void operate(double price, double low, String company){
double percent = (price/low-1)*100;
double rpercent = Math.round(percent * 100.0) / 100.0;
StringBuilder sb = new StringBuilder(32);
if(rpercent <= 10) {
sb.append(company + " is trading at:");
sb.append("the current price is: " + price);
sb.append("the 52 week low is: " + low);
sb.append("percent of 52 week low is: " + rpercent);
}
}
}
The operate method is called in a for loop in my main method 506 times and I would like to take all 506 sb string and create a super string of all the results
I hope I do not underestimate the depth of the question or have your question wrong, but to me it sounds like you are asking for the static keyword?
class SomeClass {
static StringBuilder accumulator = new StringBuilder();
public String superString (String sb) {
SomeClass.accumulator.append(sb);
return ssb.toString();
}
}
This is simple usecase of the Java static keyword. Since accumulator is declared static there will be a single instance of the variable. And this single instance will be accessed by instances of the class SomeClass. For example:
SomeClass a;
SomeClass b;
a.superString("aaa");
b.superString("bbb");
// now accumulator.toString() returns "aaabbb"
Declare that string builder as the static member containing class and initialize it only once
static StringBuilder ssb;
public static String superString (String sb) {
if(ssb == null)
ssb = new StringBuilder(32);
ssb = ssb.append(sb);
return ssb.toString();
}
For this kind of probelm you've two choice :
Simple : create a static variable in the Java class, and manipulate it.
improve : create a design model which support your need.
Ex 1 :
public class Operators {
private static String text ="";
public static String superString(String sb) {
if (sb != null) {
text = text.concat(sb);
}
return text;
}
}
Ex 2 : you can use a Collecion or a List of strings.
This is poor OOP design. You would be much better off creating a class for Stock objects and overriding toString in the Stock class(or creating some other simple output method). Then add each instance of Stock to an array and call the each object's toString (or other output method you defined).
Why the next method does not print nothing but when i change the String s to array , it works Properly?
not working:
public String toString(){
//In-Order - left,root,right.
String s ="";
toString(root,s);
return s;
}
public void toString(BSTNode root,String s){
if (root!=null){
toString(root.left,s);
s=s+","+ root.data;
toString(root.right,s);
}
}
working:
public String toString(){
//In-Order - left,root,right.
String[] s =new String[1];
s[0]="";
toString(root,s);
return s[0];
}
public void toString(BSTNode root,String[] s){
if (root!=null){
toString(root.left,s);
s[0]=s[0]+","+ root.data;
toString(root.right,s);
}
When you create an array of String and pass, basically it is creating String object (like we create using new operator). So it sues the same reference and modifies the String as you work on it. But in the former case, it treat them as two separate variable like the primitive type are handled in java.
public class StringTest {
public static void main(String[] args) {
String s[] = new String[1];
System.out.println("before: "+s[0]);
updateString(s);
System.out.println("after: " + s[0]);
}
private static void updateString(String s[]) {
s[0] = "New String";
}
}
output of the program is:
before: null
after: New String
Otherwise, it does not print anything.
The reason is, that String is not a normal Reference-Type. If you change a String a new String is generated and the modified one is returned (String is immutable). (See String.replace() for example)
If you change your method to look like this, it should probably work:
public String toString(){
//In-Order - left,root,right.
return toString(root,s);
}
public String toString(BSTNode root,String s){
if (root!=null){
return toString(root.right,toString(root.left,s)+","+root.data);
}
return "";
}
Strings in java are immutable, this means that every time you assign them a new value a new object is actually created and the reference changes.
I want to list all names that end with "Reda" and ignore case sensitivity, I have tried the condition in the toString method at the bottom, but it would not print any thing.
public class Customer {
public static void main(String[] args) throws IOException {
File a = new File("customer.txt");
FileWriter v = new FileWriter(a);
BufferedWriter b = new BufferedWriter(v);
PrintWriter p = new PrintWriter(b);
human Iman = new human("Iman", 5000);
human Nour = new human("Nour", 3500);
human Redah = new human("Redah", 0);
human iman = new human("iman", 200);
human MohamedREDA = new human("MohamedREDA", 3000);
human Mohamed_Redah = new human("Mohamed Redah", 2000);
human[] h = new human[6];
h[0] = Iman;
h[1] = Nour;
h[2] = Redah;
h[3] = iman;
h[4] = MohamedREDA;
h[5] = Mohamed_Redah;
p.println(Iman);
p.println(Nour);
p.println(Redah);
p.println(iman);
p.println(MohamedREDA);
p.println(Mohamed_Redah);
p.flush();
}
}
class human {
public String name;
public double balance;
public human(String n, double b) {
this.balance = b;
this.name = n;
}
#Override
public String toString() {
if (name.equalsIgnoreCase("Reda") && (name.equalsIgnoreCase("Reda"))) {
return name + " " + balance;
} else
return " ";
}
}
Please avoid putting condition in toString method. Remove the condition there
public String toString() {
return name + " " + balance;
}
and change your logic in Customer class
human[] h = new human[6];
h[0] = Iman;
h[1] = Nour;
h[2] = Redah;
h[3] = iman;
h[4] = MohamedREDA;
h[5] = Mohamed_Redah;
for (int i = 0; i < h.length; i++) {
if (h[i].name.toLowerCase().endsWith("reda")) { // condition here
p.println(h[i]);
}
}
And make use of loops do not duplicate the lines of code.Every where you are manually writing the lines.
Check Java String class and use required methods to add condition.
String redahname = ("Redah").toLowerCase(); //put your h[0] instead of ("Redah")
if(name.endsWith("redah")){ //IMPORTANT TO BE IN LOWER CASE, (it is case insenitive this way)
//your code here if it ends with redag
System.out.println(redahname);
} //if it does not end with "redah" it wont out print it!
You can use this, but can you please explain your question more? What exactly do you need?
try this
#Override
public String toString() {
if (name.toLowerCase().endsWith("reda"))) {
return name + " " + balance;
} else
return " ";
}
String.equals() is not what you want as you're looking for strings which ends with "Reda" instead of those equal to "Reda". Using String.match or String.endsWith together with String.toLowerCase will do this for you. The following is the example of String.match:
public class Reda {
public static void main(String[] args) {
String[] names = {"Iman", "MohamedREDA", "Mohamed Redah", "reda"};
for (String name : names) {
// the input to matches is a regular expression.
// . stands for any character, * stands for may repeating any times
// [Rr] stands for either R or r.
if (name.matches(".*[Rr][Ee][Dd][Aa]")) {
System.out.println(name);
}
}
}
}
and its output:
MohamedREDA
reda
and here is the solution using endsWith and toLowerCase:
public class Reda {
public static void main(String[] args) {
String[] names = {"Iman", "MohamedREDA", "Mohamed Redah", "reda"};
for (String name : names) {
if (name.toLowerCase().endsWith("reda")) {
System.out.println(name);
}
}
}
}
and its output:
MohamedREDA
reda
You shouldn't put such condition in toString() method cause, it's not properly put business application logic in this method.
toString() is the string representation of an object.
What you can do, is putting the condition before calling the toString() , or making a helper method for this.
private boolean endsWithIgnoringCase(String other){
return this.name.toLowerCase().endsWith(other.toLowerCase());
}
None of your humans are called, ignoring case, Reda, so your observation of no names printed is the manifestation of properly working logic.
Your condition is redundant: you perform the same test twice:
name.equalsIgnoreCase("Reda") && (name.equalsIgnoreCase("Reda"))
If you need to match only the string ending, you should employ a regular expression:
name.matches("(?i).*reda")
toString is a general-purpose method defined for all objects. Using it the way you do, baking in the business logic for just one special use case, cannot be correct. You must rewrite the code so that toString uniformly returns a string representation of the object.