how to make more than condition in toString method - java

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.

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.

Java: pass in a string and store it

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

How to pass a String value to another class in Java

Currently, I am running into a problem in my Java code. I am somewhat new to Java, so I would love it if you kept that in mind.
My problem is with passing a String value from one class to another.
Main Class:
private static void charSurvey()
{
characterSurvey cSObj = new characterSurvey();
cSObj.survey();
System.out.println();
}
Second:
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Scanner;
public class characterSurvey
{
public void survey(String character)
{
Scanner s = new Scanner(System.in);
int smartChina = 0,smartAmerica = 0,dumbAmerica = 0;
String answer;
System.out.println("Are you good with girls?");
System.out.println("y/n?");
answer = s.nextLine();
if(answer.equalsIgnoreCase("y"))
{
smartChina = smartChina - 3;
smartAmerica = smartAmerica + 2;
dumbAmerica = dumbAmerica + 4;
}
//...
//ASKING SEVERAL OF ABOVE ^
List<Integer> charSelect = new ArrayList<Integer>();
charSelect.add(smartChina);
charSelect.add(smartAmerica);
charSelect.add(dumbAmerica);
Collections.sort(charSelect);
Collections.reverse(charSelect);
int outcome = charSelect.get(0);
if(smartChina == outcome)
{
character = "smartChina";
}
else if(smartAmerica == outcome)
{
character = "smartAmerica";
}
else if(dumbAmerica == outcome)
{
character = "dumbAmerica";
}
System.out.println(character);
s.close();
}
}
When I call the first class I am trying to grab the value of the second.
Disclaimer* the strings in this class were not meant to harm anyone. It was a joke between myself and my roommate from China, thanks.
It seems as if you want to obtain the character in your main class after the survey has completed, so it can be printed out in the main method.
You can simply change your void survey method to a String survey method, allowing you to return a value when that method is called:
class CharacterSurvey {
public String takeSurvey() {
//ask questions, score points
String character = null;
if(firstPerson == outcome) {
character = "First Person";
}
return character;
}
}
Now, when you call this method, you can retrieve the value returned from it:
class Main {
public static void main(String[] args) {
CharacterSurvey survey = new CharacterSurvey();
String character = survey.takeSurvey();
System.out.println(character);
}
}
There are several mistakes here.
First off, in your main class as you write you call the method survey() on the CharacterSurvey object but the survey itself the way it is implemented needs a String parameter to work
public void survey(String character)
Also this method returns void. If you want somehow to grab a string out of that method you need to declare the method as
public String survey() {}
this method returns a string now.
If i were to give a general idea, declare a String variable in the second class which will be manipulated inside the survey method and once the survey is declared as a String method return the value at the end inside the method.
By doing that you'll be able to receive the String value by calling the method on the characterSurvey object (and of course assign the value to a string variable or use it however).
Hope this helped

java,returning null value from method

I need to return finalString value for input operator name.
where,internalPrestring is fixed for specific operator,internalDigit would be retrieved from getting operator name.then all of'em would be added to finalString.
but it is giving null, i can't understand the problem
import java.io.*;
import java.lang.*;
class CallManager
{
public static final String postString = "#";
StringBuilder stringBuilder;
String internalPreString;
String preString;
String middleString;
String finalString;
String operatorName;
int internalDigit;
//needs to set oprator name
public void setOperatorName( String getMeFromPreferences)
{
operatorName = getMeFromPreferences;
System.out.println("I got it " + operatorName);
}
//afeter having operator name need to set inrernal digit for each operator
public void setOperatorBasedInternalDigit(int getIntegerForOperator)
{
internalDigit = getIntegerForOperator;
System.out.println("I got it too " + internalDigit);
}
//it needs to get string from ocr
public void setString( String getMeFromOCR )
{
middleString = getMeFromOCR;
}
//preString creator for differnet operator
public String getOperatorBasedPreString(String operatorName)
{
if(operatorName.equals("Airtel"))
internalPreString = "787";
else if(operatorName.equals("Banglalink"))
internalPreString = "123";
else if(operatorName.equals("Grameen"))
internalPreString = "555";
else if(operatorName.equals("Robi"))
internalPreString = "111";
else if(operatorName.equals("TeleTalk"))
internalPreString = "151";
stringBuilder.append("*").append(internalPreString).append("*");
preString = stringBuilder.toString();
return preString;
}
//get operator name and retrive midlle string's digit size from it
public int getOperatorBasedInternalDigit( String operatorName)
{
if(operatorName.matches("^Airtel | Grameen | Robi$"))
internalDigit = 16;
else if(operatorName.matches("^Banglalink$"))
internalDigit = 14;
else if(operatorName.matches("^TeleTalk$"))
internalDigit = 13;
return internalDigit;
}
//check operator-based digit number with input middle string as a number then retrive final string
public String getString( String toBeInserted, int inetrnalDigit)
{
if(toBeInserted.length() == internalDigit)
{
int counter = 0;
char [] insertHere = new char[internalDigit];
for(int verifier = 0; verifier < internalDigit; verifier ++)
{
insertHere[verifier] = toBeInserted.charAt(verifier);
if(!Character.isDigit(insertHere[verifier]))
break;
counter ++;
}
if(counter == internalDigit)
{
stringBuilder.append(preString).append(toBeInserted).append(postString);
finalString = stringBuilder.toString();
//to see what i've got finally as input for using this call manager method.it would be removed too
System.out.println(finalString);
return finalString;
}
else
{
//this printing could be used in main program
System.out.println("number is less or more than desired ..... INVALID SCAN");
System.out.println(middleString);
//here i will call the method for scan the card again
//
//
return middleString;
}
}
else
{
//this printing could be used in main program
System.out.println("number is less or more than desired ..... INVALID SCAN");
System.out.println(middleString);
//here i will call the method for scan the card again
//
//
return middleString;
}
}
}
//tester class that CallManager works rightly or not
class CallManagerDemo
{
public static void main(String args[]) throws IOException
{
BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter name of Operator");
CallManager clm = new CallManager();
clm.setOperatorName("Banglalink");
System.out.println(clm.internalPreString);
System.out.println(clm.preString);
}
}
You are having only four lines that deals with your CallManager class:
CallManager clm = new CallManager();
clm.setOperatorName("Banglalink");
System.out.println(clm.internalPreString);
System.out.println(clm.preString);
The reason why you are getting null :
You are using a default constructor right and there processing is
done in it. So this is not a problem
Now on next line you call setOperator method which has this code:
public void setOperatorName( String getMeFromPreferences)
{
operatorName = getMeFromPreferences;
System.out.println("I got it " + operatorName);
}
Now here you are only setting thw variable operatorName and nothing else. So all other variables are null as you not doing any processing or something that will initialize them to something.
So when you print clm.internalPreString and clm.preString you get null as they are not initialized. But try printing clm.operatorName and it will print the operator name that you passed and was initialzed inside your method setOperatorName.
So as you have defined so many method inside your class, use them so that all the variables are set as per your logic
UPDATE
public void setOperatorName( String getMeFromPreferences)
{
operatorName = getMeFromPreferences;
//call any methods for example and use the values returned from the method by storing it inside a variable
String mystring = getOperatorBasedPreString(String operatorName)
}
You have never set the values for the variables for those you are getting the NULL value.The terms get/set must be used where an attribute is accessed directly.Read Java Programming Style GuideLines For more clarity.Use appropriate getters and setter for getting and setting the value like you have done for operatorName.
Don't you think that you should call any of the function instead of the string variables using object.
You are just calling one function that is
public void setOperatorName(String getMeFromPreferences) {
operatorName = getMeFromPreferences;
System.out.println("I got it " + operatorName);
}
You are calling default constructor with out any variable setting there,
You had not initialized any String you are calling form object.
I think you should call any of the function e-g
public int getOperatorBasedInternalDigit(String operatorName)
OR
public String getString(String toBeInserted, int inetrnalDigit)
Then you will get some string as you are expecting ...
Hope this will help you.

Behavior of return statement in catch and finally

public class J {
public Integer method(Integer x)
{
Integer val = x;
try
{
return val;
}
finally
{
val = x + x;
}
}
public static void main(String[] args)
{
J littleFuzzy = new J();
System.out.println(littleFuzzy.method(new Integer(10)));
}
}
It will return "10".
Now I just replace Return type Integer to StringBuilder and Output was changed.
public class I {
public StringBuilder method(StringBuilder x)
{
StringBuilder val = x;
try
{
return val;
}
finally
{
val = x.append("aaa");
}
}
public static void main(String[] args)
{
I littleFuzzy = new I();
System.out.println(littleFuzzy.method(new StringBuilder("abc")));
}
}
OutPut is "abcaaa"
So, Anybody can explain me in detail.?
what are the differences.?
Just because integer in immutable so after method returns even if value is changed in method it does not reflect, and does reflect in StringBuilder Object
EDIT:
public class J {
public String method(String x) {
String val = x;
try {
return val;
} finally {
val = x + x;
}
}
public static void main(String[] args) {
J littleFuzzy = new J();
System.out.println(littleFuzzy.method("abc"));
}
}
The principal operations on a StringBuilder are the append and insert methods, which are overloaded so as to accept data of any type. Each effectively converts a given datum to a string and then appends or inserts the characters of that string to the string builder. The append method always adds these characters at the end of the builder; the insert method adds the characters at a specified point.
For example, if z refers to a string builder object whose current contents are "start", then the method call z.append("le") would cause the string builder to contain "startle", whereas z.insert(4, "le") would alter the string builder to contain "starlet".
In general, if sb refers to an instance of a StringBuilder, then sb.append(x) has the same effect as sb.insert(sb.length(), x). Every string builder has a capacity. As long as the length of the character sequence contained in the string builder does not exceed the capacity, it is not necessary to allocate a new internal buffer. If the internal buffer overflows, it is automatically made larger.
Instances of StringBuilder are not safe for use by multiple threads. If such synchronization is required then it is recommended that StringBuffer be used.
In above method, finally block is calling everytime.
When an object is passed, the copy of its reference gets passed and you can change the contents if it is mutable.

Categories