1

Im having trouble with an IF statement which is to check to see if there is a value in an array or not, and if not then +1 to be added to InvalidLine.

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class Assignment {

public static void main(String[] args) throws FileNotFoundException {

    Scanner scan = new Scanner(new File("../Text.txt")); 

    String line; 

    while (scan.hasNext()) {

        line = scan.nextLine();

        String[] elements = line.split(":");

        System.out.println("The line has " + elements.length
                + " elements.");

        for (int i = 0; i < elements.length; i++) {

            System.out.println("Element " + (i + 1) + " was : " + elements[i]);


             int InvalidLine = 0;


             if (elements[i] == "");{

             Invalid++; }

             System.out.println("Invalid Fields " + InvalidLine);

        }

    }

}

}

When the output generates, +1 is added to InvalidLine even though in some cases there is no data in the [1]array

The line had 4 elements.

Element 1 was :

1

Element 2 was : biscuits

1

Element 3 was : 3

1

Element 4 was : 4

1

The line had 4 elements.

Element 1 was : Coffee

1

Element 2 was : Cake

1

Element 3 was : 3

1

Element 4 was : 6

1

1 Answers1

1
elements[i] == ""

You should never compare String like that, use

elements[i].equals("")

or

elements[i].isEmpty() // Since Java 6
ToYonos
  • 16,469
  • 2
  • 54
  • 70