Reputation: 1
I apologize for the messy code, but these are two methods are ones we are supposed to use. I have to find the word end
in a given string, if there is no end in the string return an empty string. ex (the, end said the author) output= the end
public class end {
/**
* find first apperance of the word end.
* return the string up to word end
* return empty string if the word end isn't there
*/
public static int endArray(String[] words) {
int end = 0;
for (int i = 0; i < words.length; i ++) {
end ++;
if (words[i] == "end") {
end++;
} else {
end = -1;
}
}
}
public static String end(String[] words) {
String end = "-1";
for (int i = 0; i < words.length; i ++) {
end+= words[i];
if (words[i] == "end") {
System.out.println(words[i-1]);
end++;
}
}
return end;
}
}
Upvotes: 0
Views: 327
Reputation: 56
Try this code:
import java.util.*;
public class Main
{
public String getSortedGrades(String[] arg){
String newStr = "";
for(int i=0; i<arg.length; i++){
if(arg[i]=="end"){
newStr+=arg[i];
return newStr;
}else{
newStr+=arg[i]+" ";
}
}
return newStr.contains("end")?newStr: " " ;
}
public static void main(String []args){
System.out.println("Hello World");
Main m =new Main();
String[] input ={"the", "end", "said", "the", "author"};
String s = m.getSortedGrades(input);
System.out.println(s);
}
}
Upvotes: 0
Reputation: 2821
First of all, you should know, that it's incorrect to compare strings with ==
use the equals
method instead:
if ("end".equals(words[1])) { ...
I'd implement it like that:
public static String end(String[] words) {
String allStrings = ""; // actually, it'd be better to use StringBuilder, but for your goal string concatination is enough
for (int i = 0; i < words.length; i++) {
if ("end".equals(words[i])) {
return allStrings;
}
allStrings += words[i]; // maybe here we should add spaces ?
}
// the word 'end' hasn't been found, so return an empty string
return "";
}
Upvotes: 1