I am writing a specific java code that replaces four letter words with FRED, changed words that end with ED to ID (example BED to BID) and switches words that start with DI to ID. I am not quite sure how to do step 2 and 3 (ED to ID & DI to ID.)
Here is what I have so far (what I have so far is to switch four letter words with FRED)
package KingFred;
import java.util.Scanner;
public class KingFredofId {
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
String king = input.nextLine();
for (int i = 0; i < king.length(); i )
{
if(king.charAt(i)==4)
{
}
}
System.out.println("FRED");
for (int i = king.length() - 2; i >=0; i )
{
System.out.println("ID");
}
}
}
Here is an example of what it would look like if the code was written properly.
CodePudding user response:
There are many issues here, I think you are lacking some fundamentals.
- king.charAt(i)==4 tests if your input contains the ASCII value 4 in the place i, not if the size of the input is 4.
- if you want to replace 4 letter words with "FRED" you should not have a loop, you should just look at the size of the input with an if, like this: if(king.length() == 4)
- The second condition is also wrong. first of all you are printing inside a loop, meaning it's going to print "ID" a certain amount of time, NOT once like you want
- I don't know where to begin, but the second loop is wrong in every way.
But more generally, you have the wrong approach, none of these require loops at all.
Changing 4 letters characters to "FRED" requires you to test the size of the string and then in this case printing fred if the size is 4
The correct way of doing #2 and #3 would be to use string.substring, so for example king.substring(0, 2) will get you the first two characters, and you can compare these.
CodePudding user response:
You can do this easily with regex:
public static List<String> fredOfId(String sentence) {
List<String> words = new ArrayList<>();
for (String word : sentence.split("\\W")) {
word = word.trim();
if (word.length() == 4) {
words.add("FRED");
} else {
words.add(word.replaceAll("(\\bdi|ed\\b)", "id").toUpperCase());
}
}
return words;
}