I'm trying to do this java practice exercise I've found online. My output should be:
bojackhorseman is the longest name with 14 characters and is at position 3
tom is the shortest name with 3 characters and is at position 0
27 //(total of all carachters in array)
bob|jimmy|danny|bojackhorseman| //(all the names seperated by a |)
This is exactly what my output below is, but I feel like it is over programmed. I know that the last for loop is not necessary. I want to condense my code by taking the result of the last for loop(the names in the array separated by a pipe symbol) and store that value into a string, let's call it pipe. Then, at the bottom of my program, system.out.println(pipe); I feel like that would be much cleaner then another unnecessary for loop. Every time I try that though, I can't get it to print all the names. What am I not doing right? Thanks in advance.
Also, I want to keep it as simple as I have it below without adding any methods or functions or anything like that. I want to just simplify the last for loop and store it in a string then print put the string at the end.
public class Practice {
public static void main(String[]args){
String[] names = {"tom", "jimmy", "danny", "bojackhorseman"};
String long=names[0];
String short=names[0];
int lLocation=0;
int sLocation=0;
int tot=0;
for(int x=0; x < names.length; x++){
if(names[x].length() > long.length()){
long=names[x];
lLocation=x;
} if (names[x].length() < short.length()) {
short=names[x];
sLocation=x;
} tot=tot + names[x].length();
} System.out.println(long + " is the longest name with " +
long.length() + " characters and is at position " + lLocation);
System.out.println(short + " is the shortest name with " +
short.length() + " characters and is at position " + sLocation);
System.out.println(tot);
for(int j=0; j < names.length; j++){
System.out.print(names[j] + "|");
}
}
}
Aucun commentaire:
Enregistrer un commentaire