Pregunta

I am reading a file that contains the following:

127.0.0.1:8080

127.a.0.10:8081

127.0.1:8080.1

127.0.10.5:-8080

From there I have to print out the strings that match the following format. ###.#.#.#:#### This # represents any positive integer. When I run the code, it prints out the first line, and the statement "Not valid" for the next three strings, but it also marks an error.

Exception in thread "main" java.lang.NullPointerException at homework4.Main.main(Main.java:36)

How can I fix this? Does it have to do with inputStream = null? Thanks in advance.

            public static void main(String[] args) 
            {
                Scanner inputStream = null;
                int count1 = -1;
                int i = 0;
                final String[] content = new String[200];
                {
                    try
                    {
                        inputStream = 
                                new Scanner (new FileInputStream ("input.txt"));
                    }
                    catch (FileNotFoundException e)
                    {
                        System.out.println("File input.txt could not be found or could not be opened");
                        System.exit(0);
                    }
                }
                while (inputStream.hasNext())
                {
                    content[++count1] = inputStream.nextLine();
                }


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


                    if ( content[i].matches("^\\d{3}\\.\\d{1}\\.\\d{1}\\.\\d{1}\\:\\d{4}"))
                    {

                        System.out.println(content[i]);
                    }

                    else 
                    {
                        System.out.println("Not Valid");
                    }
                }
            }}
¿Fue útil?

Solución

If your purpose is just print , then you don't need to store and don't required String[] content .. Just read the line and validate the line falls in particular pattern.

Move the condition to while loop.

 while (inputStream.hasNext())
   {
         String content = inputStream.nextLine();
          // Move the condition and check with content variable.
               if ( content.matches("^\\d{3}\\.\\d{1}\\.\\d{1}\\.\\d{1}\\:\\d{4}"))
                {

                    System.out.println(content);
                }

                else 
                {
                    System.out.println("Not Valid");
                }
   }

In case your purpose is store the content . When you don't know the size / number of lines up ahead like this case , use List to store which can grow dynamically as required.

Like

List<String> contents = new ArrayList<String>() 

And add the valid line with in valid condition like this.

  contents.add(content);

Otros consejos

if (content[i] != null) {   //check for this
    if (content[i].matches("^\\d{3}\\.\\d{1}\\.\\d{1}\\.\\d{1}\\:\\d{4}")) { ... }
    else { ... }
}
    Path path = Paths.get("input.txt");
    List<String> strings = Files.readAllLines(path, Charset.defaultCharset());
    for(String string: strings) {
        if (string.matches("^\\d{3}\\.\\d{1}\\.\\d{1}\\.\\d{1}:\\d{4}")) {
            System.out.println(string);
        } else {
            System.out.println("not valid");
        }
    }

If you use java 8, you can use Streams API

    Path path = Paths.get("input.txt");
    List<String> strings = Files.readAllLines(path);
    strings.stream()
            .forEach(string -> {
                if (string.matches("^\\d{3}\\.\\d{1}\\.\\d{1}\\.\\d{1}\\:\\d{4}")) {
                    System.out.println(string);
                } else {
                    System.out.println("not valid");
                }
            });

note : your regex contains a redundant escape

use

^\\d{3}\\.\\d{1}\\.\\d{1}\\.\\d{1}:\\d{4}

instead of

^\\d{3}\\.\\d{1}\\.\\d{1}\\.\\d{1}\\:\\d{4}

In your for-loop you go from 0 to length. The last index is although (length - 1)

Another problem is if your file has more than 200 lines

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top