1

Before I start I'd like to say; I have asked this question before and was flooded by ways I could change my program instead of explicit answers to my question - I am happy with my code I just want to validate it :)

Like the title implies I am trying to validate my string array, I am new to Java and have been trying to put several boolean conditions within the for loop however the code always seems to ignore the loop and proceed as normal for example if I write "if (words == null) print "Error"" the program runs as normal as though the condition was not there even when an array place is empty.

String [] football_list = new String [100];         //Declare the array 
int counter = 0;                                //Initialize counter integer

scanner = new Scanner(System.in);{      //Import Scanner
System.out.println("Input as follows; "); {     //User instructions
System.out.println("Home team : Away team : Home score : Away score");

String line = null; { // Creates a blank string

while (!(line = scanner.nextLine()).equals("")) { // The code in the loop will process only if it is not empty

    if (line.equals("quit")) { // When the user is finished this exits the program
           break;
    } else {
        football_list[counter] = line; // The below String is printed for the amount of values inside the counter integer

        System.out.println("Home team : Away team : Home score : Away score");
    }

    counter++;  // counter is incremented
}

}
for (int i = 0; i < counter; i++) { // A loop to control the Array 
    String[] words = football_list[i].split(":"); // Splits the input into 4 strings
    if(words.equals(null)){

        System.out.println("Null");
        }
    else
    System.out.println(words[0].trim() + " [" + words[2].trim() + "]" + " | " + words[1].trim() + " [" + words[3].trim() + "]"); // Formats and prints the output    

    }



}
    }
        }
            }   

My code creates a sports result table from user input. The user enters input like so "Home_Team : Away_Team : Home_Score : Away_Score", I want to produce an error message and stop the program once one of the slots is empty.

New error

for (int i = 0; i < counter; i++) { // A loop to control the Array 
    String[] words = football_list[i].split(":"); // Splits the input into 4 strings
    if (words.length != 4) { // If the length of the array elements does not equal 4 then print error message
        System.out.println("Input was not valid");
        //counter--;
        //i--;
    } else
    {

    System.out.println(words[0].trim() + " [" + words[2].trim() + "]" + " | " + words[1].trim() + " [" + words[3].trim() + "]"); // Formats and prints the output    


   }
   }
   }
    System.out.println("                 ");
    System.out.println("                 ");
    System.out.println("                 ");
    System.out.println("        Totals        ");
    System.out.println("-------------------------");
    System.out.println("Total games played: " +  counter);


    }
Tino Uchiha
  • 53
  • 1
  • 10
  • Please clarify what's happening, and what *should* be happening. And reducecyour code tobthe minimum that shows the problem. – Bohemian Dec 27 '16 at 19:37

2 Answers2

1

If you're trying to detect inputs like

Tigers:Lions:7

Find the length of words and check to see if it is four.

if (words.length != 4){

    System.out.println("Input was not valid.");
}
else{
    // Print formatted string 
}

On another note, make sure that you understand that an empty array/string and a null array/string are not the same. An empty array {} or an empty string "" has a value, even though it's empty.

String[] words = football_list[i].split(":"); // Splits the input into 4 strings
if(words.equals(null)){
    System.out.println("Null");
}

Here, words will never be null because you have initialized it to football_list[i].split(":"). Also, note that it will never be an empty array either.

If : is not found in football_list[i], the array will have one element and words[0] = football_list[i].

Initializing something to null isn't useful because String line; already has line to be null.

Full code should look something like:

import java.util.Scanner;

public class circle {
    public static void main(String[] args) {
        String[] football_list = new String[100]; // Declare the array
        int counter = 0; // Initialize counter integer

        Scanner scanner = new Scanner(System.in); // Import Scanner
        System.out.println("Input as follows; "); // User instructions
        System.out.println("Home team : Away team : Home score : Away score");

        String line = null; // Creates a blank string

        while (!(line = scanner.nextLine()).equals("")) { // The code in the
                                                        // loop will process
                                                        // only if it is not
                                                        // empty

            if (line.equals("quit")) { // When the user is finished this exits
                                    // the program
                break;
            } else {
                football_list[counter] = line; // The below String is printed
                                            // for the amount of values
                                            // inside the counter integer

                System.out.println("Home team : Away team : Home score : Away score");
            }

            counter++; // counter is incremented
        }

        for (int i = 0; i < counter; i++) { // A loop to control the Array
            String[] words = football_list[i].split(":"); // Splits the input
                                                        // into 4 strings
            if (words.length != 4) {
                System.out.println("Input was not valid.");
            } else
                System.out.println(words[0].trim() + " [" + words[2].trim() + "]" + " | " + words[1].trim() + " ["
                    + words[3].trim() + "]"); // Formats and prints the output

        }

    }
}

Consider using a validator method, since there is a lot of validating to do.

It would look something like this:

public static boolean validateString(String input) {
    if (input.split(":").length != 4) {
        return false;
    }
    for (String info : input.split(":")) {
        if (info.length() == 0) {
            return false;
        }
    }
    return true;
}

and your for-loop logic could be

for (int i = 0; i < counter; i++) { // A loop to control the Array
        String[] words = football_list[i].split(":"); // Splits the input
                                                        // into 4 strings
        if (Main.validateString(football_list[i])) {
            System.out.println(words[0].trim() + " [" + words[2].trim() + "]" + " | " + words[1].trim() + " ["
                    + words[3].trim() + "]"); // Formats and prints the output
        }
        else{
            System.out.println("Your input of " + football_list[i] + " was not valid.");
        }
    }

Also, consider using an ArrayList instead of an array. You wouldn't have to keep a counter or set the maximum number of inputs to be 100.

j1119
  • 143
  • 1
  • 8
  • Oh I was not aware my mistake I understand now, but I am not too sure on whether Im placing the condition in the correct place. I placed the above code within the for loop however it still did not work as the logic implied – Tino Uchiha Dec 27 '16 at 17:52
  • The for loop should only contain the if/else statements. Also, if the code you originally posted is verbatim, there are a lot of extra `{`s, like in lines 4 and 5. Check my edited post for the full code. – j1119 Dec 27 '16 at 19:16
  • Wow yes that works well. In the case of an input like "Home_Team : Away_Team : Home_Score :" which contains a fourth ":" is there a way to also print an error. – Tino Uchiha Dec 28 '16 at 13:25
  • Right now it prints the error message only if there are less than four splits ":", if there is a split that contains nothing after can that also create an error message is what I'm asking – Tino Uchiha Dec 28 '16 at 13:27
  • The example I gave you prints like this "Home_Team [Home_ Score] | Away_Team" - a perfect output would be "Home_Team [Home_Score] | Away_Team [Away_Score] – Tino Uchiha Dec 28 '16 at 13:30
  • Simply check if all elements in `words` has length greater than 0. – j1119 Dec 28 '16 at 21:35
  • Since there's a lot of validation to do, you could create a `validate` method that takes a string and returns a boolean. – j1119 Dec 28 '16 at 21:39
  • Wow, that does make a lot of sense very grateful. I'm not going to lie though I'm new to Java and I'm pretty overwhelmed and don't know where to begin implementing this code I suck - I've haven't learnt about methods yet. Could you give me an example on the "check if all elements in words has length greater than 0", I will try understand this then go onto revising the latter. – Tino Uchiha Dec 30 '16 at 15:52
  • This is an example of an advanced for-loop, or a for-each loop. If you have an array of strings, you can use `for (String text: array)`, which iterates through the array just as `for (int i = 0; i < array.length; i++)` would, but instead of using `array[i]` to test for the length of each string, you can just use `text`. It's cleaner to use a for-each loop most of the time. – j1119 Dec 31 '16 at 21:18
  • The exact details might be a little bit confusing for your skill level now, but see this link to see how it works. http://stackoverflow.com/questions/85190/how-does-the-java-for-each-loop-work – j1119 Dec 31 '16 at 21:19
  • Thank you very much sir it's appreciated – Tino Uchiha Jan 01 '17 at 20:03
  • Hi again, I have a problem which is truly killing me. I have implemented a new code which feedbacks the amount of games played (I have attached it ) however now if I chose to input anything with less than 4 elements FIRST the rest of the inputs will be deemed incorrect just like it. – Tino Uchiha Jan 05 '17 at 15:36
  • For example, if I input a score with less than 4 elements, the rest of the scores I input will be deemed incorrect with the Sysout "Invalid Input" even when they are correct – Tino Uchiha Jan 05 '17 at 15:37
  • I know you commented out two lines of code in the if statement, decrementing counter and i. Does the error occur when these lines are commented out? – j1119 Jan 05 '17 at 16:38
  • I'm not sure what the point of counter is. If you want to keep track of how many items are in the array, you can always use `football_list.length`. – j1119 Jan 05 '17 at 16:39
  • Also, keep your code clean. There are style guidelines that exist for a reason; it keeps code maintainable, easy-to-read, and thus easy to debug. Get rid of things like `{ }` and make sure your brackets are aligned consistently. – j1119 Jan 05 '17 at 16:41
  • Oh sorry my mistake, the error only occurs when those lines are not commented out, also the length of football_list is 100 - the counter is there to record the amount of user inputs only – Tino Uchiha Jan 05 '17 at 17:23
0

What if you do something like this to check whether the array is null or empty:

if(words[0] != null && words[0].length() > 0) {
   //it is not null and it is not empty
}else{
   //you can have the error message here
   System.out.println("It's null or empty");
}
Kulasangar
  • 9,046
  • 5
  • 51
  • 82
  • Hi thanks, this is the output of your code: Leeds [2] | Liverpool [1] 4 Leeds [2] | Liverpool [1] 4 Leeds [2] | [1] I input the first two scores correctly and the last with one array empty - It still printed the incorrect input however with no error message – Tino Uchiha Dec 27 '16 at 17:30
  • @TinoUchiha i've edited the answer with another code change, if you can check and let me know? – Kulasangar Dec 27 '16 at 17:42