0

I'm currently practicing for my Java Practicum Exam, most importantly NachOS, here is my trouble right now. I'm stuck at developing this right now

Ask the user to input file name. The file name must contain dot (‘.’). Dot must not be in front of or in the end of the file name.

So far I've created the code like this

do {
        cs.write("Name: ");
        name = cs.read();
        Format = name.split(".");
    } while (Format.length!=1);

and the problem is that it still won't validate dot, even if I've typed the input "important.docx" for the example. can you tell why this happens and how I should solve this?

  • 1
    Leaving aside the fact that split works but it's not the best way to check for the presence of a character in a string, why are you splitting by `-` if you need to check for the presence of `.`? – Federico klez Culloca Jun 07 '20 at 12:25
  • See [`name.indexOf('.')`](https://docs.oracle.com/javase/8/docs/api/java/lang/String.html#indexOf-int-) and [`name.length()`](https://docs.oracle.com/javase/8/docs/api/java/lang/String.html#length--). – Andreas Jun 07 '20 at 12:29
  • `split(".")` will not work, since `.` is a special character in a regex. – Andreas Jun 07 '20 at 12:52
  • Is ".a.b." a legal name? It contains a dot which is not in the front of nor in the end of the file name. – Simon G. Jun 07 '20 at 12:54

1 Answers1

3

Keep it simple, Java has methods for that:

private static boolean validFileName(final String name) {
    return name.contains(".") && !name.startsWith(".") && !name.endsWith(".");
}
Patres
  • 147
  • 2
  • 20