Get method for returning initials - java

I am writing a short Java script to where I have a name in String as a variable. I want to write get method to get initials and return them for later use. That method works well when printing out the initials, but not when wanting to return that value.
//method for getting initials of the name
public String getInitials() {
String words[] = competitorName.split(" ");
for(String word : words) {
return word.charAt(0) + " ";
}
}
It shows me that the method must return a result of type String but that should already be it. And does not work even when I am adding toString methods (then it writes that it is already String)

You almost got it! Just use StringBuilder and return result
public String getInitials() {
String words[] = competitorName.split(" ");
StringBuilder builder = new StringBuilder();
for(String word : words) {
builder.append(word.charAt(0));
}
return builder.toString();
}

Related

Java - What does it mean by writing return ""; in a method?

I am a Java beginner. When reading a block of Java code, I came across a method which includes a if condition and return "";
Just wondering what does return ""; means…
The example code is below:
public String parse(String d, String u) {
if (d.isEmpty() || u.isEmpty()){
return "";
}
...
}
Could someone explain further to me please? Thank you
I'm just doing to break this down line by line for you.
public String parse(String d, String u)
This line declares a new method which:
Is called parse
Returns a string
Takes two strings as inputs
If youre wondering specifically about the fact that the keyword return is used then you can look at this answer I found from a quick google search.
if (d.isEmpty() || u.isEmpty())
This line checks if the input d is empty OR (expressed by '||') input u is empty. Essentially checking if either of the inputs are empty.
return "";
If the above if statement is met, return""; will be run. This means the method will return an empty String.
I can only guess what is at the end of the method you've posted but to help you further I've whipped up a quick example.
public String parse(String d, String u) {
if (d.isEmpty() || u.isEmpty()){
return "";
} else {
return "not empty";
}
}
public static void main(String[] args)
{
String d = "hi";
String u = ""; //empty
String result = parse(d, u);
System.out.println(result);
String d = "hi";
String u = "bye"
result = parse(d, u);
System.out.println(result);
}
The output we get in the console is:
empty
not empty
This is probably a check before starting parsing those string, you dont want to parse empty strings cause it probably has to do with the parsing mechenism, so it start from checking validation of the arguments, and return empty String if it invalid

removing characters from string using a method in java

I'm trying to write a method to take in a string as a parameter and remove all whitespaces and punctuation from it so this is my idea of how to do that..
import java.util.*;
public class Crypto {
public static void main(String[] args){
Scanner input = new Scanner(System.in);
System.out.print("Please insert the text you wish to encrypt: ");
String text = input.nextLine();
text = normalizeText(text);
System.out.println(text);
}
public static String normalizeText(String s){
s.replace(" ","");
s.replace("(","");s.replace(")","");s.replace(".","");
s.replace(",","");s.replace("?","");s.replace("!","");
s.replace(":","");s.replace("'","");s.replace("\"","");
s.replace(";","");
s.toUpperCase();
return s;
}
}
Now , I only added the text = normalize Text(text); and then printed it because it wouldn't print it to the screen without it( even though in some methods the return would actually show an output on the screen)
anyway, even this change didn't help because it doesn't remove anything from the string taken in by the method it prints out the exact same string.. any help?
Thanks in advance . :)
Problem in your code is, you haven't assigned back the new string that got generated after s.replace(":",""); Remember, strings are immutable so the change by replace method will not apply to the string object on which you call the method.
You should have written,
s = s.replace(":", "")
Instead of your tedious method normalizeText you can write your method like this,
public static String normalizeText(String s){
return s.replaceAll("[ ().,?!:'\";]", "").toUpperCase();
}
You need to make assignments to the string after each replacement has been made, e.g.
public static String normalizeText(String s) {
s = s.replace(" ", "");
s = s.replace("(","");
// your other replacements
s = s.toUpperCase();
return s;
}
But note that we can easily just use a single regex to handle your replacement logic:
public static String normalizeText(String s) {
s = s.replaceAll("[().,?!:'\"; ]", "").toUpperCase();
return s;
}

Using for : each loop to return multiple Strings nestled in an ArrayList

I'm trying to return all of the 'players and their goals' in a sports team using the following:
public String printPlayers(){
for (Player player : this.players){
return player.toString();
}
}
Netbeans says there is no return statement, which I presume is because it is within the for-each loop. But if I place it outside it will only return one item. Here is the test code:
Team barcelona = new Team("FC Barcelona");
Player brian = new Player("Brian");
Player pekka = new Player("Pekka", 39);
barcelona.addPlayer(brian);
barcelona.addPlayer(pekka);
barcelona.addPlayer(new Player("Mikael", 1));
barcelona.printPlayers();
In the Player Object, here is what toString does:
public String toString(){
return ("Player: "+this.name+", goals "+this.goals);
}
Java allows you to return only a single object. It is not possible to return multiple objects. If you want to return multiple objects from a single method, you first have to collect them into a single object, for example an array, a List or a String, and then return that.
Let's look at your code. Netbeans complains about the missing return statement because it is possible that your players collection is empty. In that case the loop block is never executed and the method end without a return statement, which is not allowed. So let's repair your method as follows:
public String printPlayers(){
for (Player player : this.players){
return player.toString();
}
return "";
}
Also now the method only returns a single object: it will convert the first player in your collection to a string and then return that. The other players are ignored. So you have to collect your players in a single object. Since you want to return a string, it makes sense to collect the strings in a single string:
public String printPlayers(){
String result = "";
for (Player player : this.players){
result += " " + player.toString();
}
return result;
}
Now you can try to make the result better, for example by removing the leading space for the first element, or by adding commas instead of spaces, etc. Also, for more performance you can use a StringBuilder for building your string (but think about performance once you have a working method!).
public String printPlayers(){
String data="";
for (Player player : this.players){
data +=player.toString();
}
return data;
}
Use a StringBuilder
public String printPlayers(){
StringBuilder sb = new StringBuilder();
for (Player player : this.players){
sb.append(player.toString());
}
return sb.toString();
}
Why netbeans complaining is, what if you not enter to for loop ?? So there should be a return always.
Coming to actual problem,
Just build a String and return
public String printPlayers(){
StringBuilder builder=new StringBuilder();
for (Player player : this.players){
builder.append(player).append(" ");
}
return builder.toString();
}
That's build a String with appending all players as String and return finally.

Invoking a toString method from another class

Below is my toString() method in which I am trying to invoke another toString() from a different class called Tree. I am trying to return each part of an ArrayList and format it into my toString() from my Tree class, then put it all into the "result" String.
So far, all my method does is go through the list and return nothing. How do I make it so it essentially puts the entire list into the result string, under the format of my toString() from my Tree class?
public String toString(){
String result;
int i = 0;
while(i < listOfTrees.size()){
listOfTrees.get(i);
i++;
}
Use a StringBuilder :
public String toString(){
StringBuilder result = new StringBuilder();
int i = 0;
while(i < listOfTrees.size()){
result.append(listOfTrees.get(i) + " "); // this would use the toString
// method of the type contained
// in this List
i++;
}
return result.toString();
}
You need to use a StringBuilder. Get each String append it to the builder and then return the final String produced by it
public String toString(){
StringBuilder str= new StringBuilder();
for(int i = 0; i < listOfTrees.size(); i++){
str.append(listOfTrees.get(i));
}
return str.toString();
}
The other way to do it is to initialize result with an empty String literal to start with and then use the + operator to add other Strings to it, but this is awfully inefficient as Strings are immutable and each time you add a String that way, you create a whole new object.

Java - Calling a method that returns a string of ints from an array

I am working with a program in which I need to use a method call to return a String from an int array. This is what I have of the method so far (I am required to use a method with this header and parameters)
public String toString()
{
for (int i=0;i<NUM_POCKETS;i++)
{
this.getPocketCount(i);
}
}
I basically need the loop to go through all of my "pockets" (array items) and return the stored values into a String to be returned.
I could be missing something very obvious, but for the life of me I do not understand how this information would be stored and returned to the Driver as a String. I know the loop logic is there, but how do I store each increment of i into a String as the loop progresses?
Thanks in advance for any help!
"I am working with a program in which I need to use a method call to return a String from an int array."
If this isn't a homework problem, you can simply use Arrays.toString(int[] array).
String myString = Arrays.toString(myIntArray);
Otherwise, maybe you can do something like this:
String getStringFromIntArray(int[] array) {
StringBuilder builder = new StringBuilder();
for (int num : array)
builder.append(num)
return builder.toString();
}
Try looking into the StringBuilder class. The specification for Java 6 is here.
http://docs.oracle.com/javase/6/docs/api/java/lang/StringBuilder.html
You would need a StringBuilder object and just append the value to the object using the .append() function.
as long as this.getPocketCount(i); gives you the value of the array on position i:
public String toString() {
String returnstring= ""; //init empty string
for (int i = 0; i < NUM_POCKETS; i++) {
returnstring += this.getPocketCount(i)+" "; //append(concat) to string
}
returnstring = returnstring.substring(0, returnstring.length()-1); //remove the last " "
return returnstring; //return string
}
the + sign appends the next string
"Hello"+" "+"World" becomes "Hello World"
Edit:
public String toString() {
String returnstring= ""; //init empty string
for (int i = 0; i < NUM_POCKETS-1; i++) { //-1 to place last later
returnstring += this.getPocketCount(i)+" "; //append to string
}
returnstring += this.getPocketCount(NUM_POCKETS-1) //append the last value
return returnstring; //return string
}
Assuming you specifically want to build your String from within the loop, you could use a StringBuilder. It is more verbose than the one-liner offered by Arrays.toString(), but you asked for it:
e.g.
public String toString() {
StringBuilder sb = new StringBuilder(NUM_POCKETS);
for (int i = 0; i < NUM_POCKETS; i++) {
sb.append(this.getPocketCount(i));
}
return sb.toString();
}
Using a StringBuilder within a loop is faster than performing concatenation of each individual element. See: when to use StringBuilder in java

Categories

Resources