Originally Posted by
Norm
Read into a variable and then test it vs doing it all in one statement. It will allow for debugging and further processing of what was read in. Don't do it this way:
if (keyboard.next().equals(forbidword))
I agree with Norm. I have always found that it is easier to debug and understand my programs when I create variables for things, whether I'm going to use it more than once or not. It is a good thing to do, especially in larger programs.
You would do something like:
String var = keyboard.next();
System.out.println(var);
if (var.equals(forbidword))
It is more lines of code, but it makes it easier to debug and fix when things go wrong.
Also, from a personal stylistic point of view, I recommend always initializing variables with basic values. I know some types have defaults, but I prefer to always initialize when I create.
For ints: I usually set them to -1, since that is usually used as an anomaly number.
For Strings: I usually set them to "" (empty String), since that will results in an empty value.
For Objects: I usually set them to null, since that indicates I never gave it a value.
I do this because it prevents compiler errors about not initializing variables when your variable setting is condition based. For you, this isnt the case, but it is a good thing to start doing.
So, instead of this:
String forbidword;
String replaceword;
int numreplaced = 0;
System.out.println("Enter word to be filtered out:");
Scanner keyboard = new Scanner(System.in);
forbidword = keyboard.next();
System.out.println("Enter replacement word:");
replaceword = keyboard.next();
I would say:
String forbidword = "";
String replaceword = "";
int numreplaced = 0;
System.out.println("Enter word to be filtered out:");
Scanner keyboard = new Scanner(System.in);
forbidword = keyboard.next();
System.out.println("Enter replacement word:");
replaceword = keyboard.next();
Once against, entirely stylistic, but it is how I prefer to do it.