Java: pass in a string and store it - java

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).

Related

Trying to loop through an array within an array

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.

How to return multiple values without using Collections?

I am using textbook Murach's java programming, and in one of the exercises, it is asking me to do the following:
add this method (given by the book):
private static String displayMultiple(Displayable d, int count)
write the code for this method so it returns a String that contains the Displayable parameter the number of times specified by the int parameter.
Displayable is an interface that implements getDisplayText(). And this method just returns a String with instance variables of an object, i.e. for an Employee, it returns first name, last name, department, and salary.
Everything works, except for the "returns a String".
This is probably an exercise about loops:
You have a way to convert d to a string: getDisplayText. This yields, say, "ABCD"
You want to return count times that string "ABCD". If count == 3, that means "ABCDABCDABCD".
Useful keywords: for loop, StringBuilder. Here is a template that you can use to get started:
String text = ;// Use getDisplayText here
StringBuilder ret = new StringBuilder();
/* Loop from 0 to count - 1 */ {
// Append `text` to `ret`
}
return ret.toString();
You don't actually need to return multiple values.
As I understand it:
private static String displayMultiple(Displayable d, int count){
String s = "";
String ss = d.getDisplayText();
for(int i=0; i<count; i++){
s += ss;
}
return s;
}
If you want to return multiple values with out using collection then you can create an Class -
public class MultipleValue{
String firstValue;
String secondValue;
//other fields
}
Then from someMethod() where you want to return multiple value (that is firstValue, secondValue) you can do this -
public MultipleValue someMethod(){
MultipleValue mulVal = new MultipleValue();
mulVal.setFirstValue("firstValue");
mulVal.setSecondValue("secondVAlue");
return mulVal;
}
Then from the calling class of someMethod() you can extract multiple values (that is firstValue and secondValue) like this -
//from some calling method
MultipleValue mulVals = someMethod();
String firstValue = mulVals.getFirstValue();
String secondValue = mulVals.getSecondValue();

how to make more than condition in toString method

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.

actual code in static method or instance method

I'm writing a small library.
public class MyClass {
public static String doSomethingWithString(final String s) {
new MyClass().doSomething(s);
}
public String doSomething(final String s) {
return null;
}
}
Or I can do like this.
public class MyClass {
public static String doSomethingWithString(final String s) {
return null;
}
public String doSomething(final String s) {
return doSomethingWithString(s);
}
}
Which style is preferable? Are they same?
UPDATE
Thank you for comments and answers.
Here are two classes.
public class IdEncoder {
private static String block(final long decoded) {
final StringBuilder builder = new StringBuilder(Long.toString(decoded));
builder.append(Integer.toString(
ThreadLocalRandom.current().nextInt(9) + 1)); // 1-9
builder.append(Integer.toString(
ThreadLocalRandom.current().nextInt(9) + 1)); // 1-9
builder.reverse();
return Long.toString(
Long.parseLong(builder.toString()), Character.MAX_RADIX);
}
public static String encodeLong(final long decoded) {
return block(decoded >>> 0x20) + "-" + block(decoded & 0xFFFFFFFFL);
}
public String encode(final long decoded) {
return encodeLong(decoded);
}
}
And another style.
public class IdDecoder {
public static long decodeLong(final String encoded) {
return new IdDecoder().decode(encoded);
}
public long decode(final String encoded) {
final int index = encoded.indexOf('-');
if (index == -1) {
throw new IllegalArgumentException("wrong encoded: " + encoded);
}
return (block(encoded.substring(0, index)) << 32)
| (block(encoded.substring(index + 1)));
}
private long block(final String encoded) {
final StringBuilder builder = new StringBuilder(
Long.toString(Long.parseLong(encoded, Character.MAX_RADIX)));
builder.reverse();
builder.deleteCharAt(builder.length() - 1);
builder.deleteCharAt(builder.length() - 1);
return Long.parseLong(builder.toString());
}
}
If you are just picking between these 2 options, take the second one.
The reason is the first requires you to allocate a new dummy object on the heap just to call a method. If there is truly no other difference, don't waste the time and space and just call the static method from the class.
The second is more akin to a static Utility function, which are a fine coding practice.
When writing a library, ease of use dramatically trumps general best practices. Your method should be static if it doesn't make sense for a user to instantiate something in order to access it. However often it is actually much cleaner and more powerful for a method to be part of an object, because it allows the user (as well as the library writer) to override it in child classes.
In a sense, you aren't actually asking a programming question, but a UX question. Ask yourself how your users would best benefit from accessing your code, and implement it that way. As a good benchmark, look at the Guava API; it consists of many static utility classes, but just as many classes and interfaces designed to be easily extended. Do what you think is best.

android/java concept to call all getter methods with a single loop

I am doing an assignment and stuck at this point:
I have a class in which i have 30 getter and setter method.
public class example{
public String get1(){
return someString1;
}
public String get2(){
return someString1;
}
public String get3(){
return someString4;
}
and so on...
public String get30(){
return someString30;
}
}
Now i want to call all getter method with a single loop like
for(int i= 1; i<=30;i++){
// String total = get1()+get2()+get3()...............
}
what should i do?
Edit: i did it using reflection :
http://docs.oracle.com/javase/tutorial/reflect/member/methodInvocation.html
Thanks Ricky
The commented code is the only way to do that. But this is a symptom that your design is incorrect. Rather than having 30 properties of type String, you should certainly have one property of type String[] or List<String>.
Then you could do:
List<String> list = getListOfStrings();
StringBuilder builder = new StringBuilder();
for (String s : list) {
builder.append(s);
}
String concatenation = builder.toString();
If these are the standard accessors then better to go for List and do get(index)
else Reflection hack will help
public class Example{
private List<Integer> marks = new ArrayList<Integer>();
now loop
for(int i= 1; i<=30;i++){
total += marks.get(i);
}
Just override the toString() method in the example class like this:
#Override
public String toString() {
return someString1 + " " + someString2 + " " + someString3;
}
I did it using reflection :
http://docs.oracle.com/javase/tutorial/reflect/member/methodInvocation.html

Categories