KSJ10
KSJ10

Reputation: 66

Is it necessary to resolve the errors shown in the output window of Netbeans IDE even if my code is working the way I want?

Say I want to get the 'of' typed in the input by the user

I am making an app, not finishing off in this dumb output screen (This is only an example)

 import java.util.*;
 Scanner input = new Scanner(System.in);
 String text = input.nextLine();
 int check = 0;
 for(int i = 0; i < text.length(); i++;){
     if(text.substring(i, i + 2) .equals("of")){
          check = 0;
     }
 }

If the user enters abofd, it surely recognises the of at position at 2-4. But when i value is 4 it checks position from 4-6, but as position 6 is not present is not present it gives an error. I know you are thinking me to set i < text.length() - 1 at line 5, but my original code needs to run until the end!

Upvotes: 0

Views: 38

Answers (1)

GhostCat
GhostCat

Reputation: 140613

It is always a good idea to validate input coming from a user, but you are very much overcomplicating things! Even worse, you wrote down outright wrong code:

String text = input.nextLine();
int check = 0;
for(int i = 0; i < text.length(); i++;){
   if(text.substring(i, i + 2) .equals("of")){

The above can't work! You see, i iterates from 0 to text LENGTH. But then you are using i+2 to get a substring from text. (so: say hello to your first ArrayIndexOutOfBoundsException).

Instead, you can do things like:

if (text.contains("of")) {

or

if (text.indexOf("of") >= 0) {

to find out if your string contains "of".

And to answer your question in the title: absolutely yes. Programming is about being a good craftsman to a very large degree. A good craftsman keeps all his tools and materials in order. He doesn't allow for mess, waste, ...

So, long story short: from day one, to all eternity: when writing code, you strive for a zero tolerance policy: no compiler errors, no warnings, nothing in your code that doesn't belong there!

Upvotes: 1

Related Questions