Substring method to identify char value in string value

Viewed 54

I have an application to create company email domains, however, I ran into a small issue when creating a loop to run an error message in case a user entered an invalid character.

I haven't been able to get it to work with what I have and so I'm sure I'm missing out something important.

System.out.println("\nEnter name: ");
String name = in.nextLine();

int length = name.length();

for (int x = 0; x < length; x++) {
    
    if(name.substring(x,x+1).equals(".")) {
        
        System.out.println("Error! - name can not contain (.) values\n"
                         + "***************************************************");
        
            System.out.println("\nWould you like to capture another name?" +
            "\nEnter (1) to continue or any other key to exit");
            String opt1 = in.nextLine();

                // If statement to run application from the start 
                if (opt1.equals("1")) {
       
                     System.out.println("menu launch");
                }
                else { System.exit(0); }
    }            
    else { break; } 
}
2 Answers

Don't reinvent the wheel. Instead of looping over the characters of the string, you could just use the contains method:

if (name.contains(".")) {
    // logic comes here...

While Mureinik is correct on the best way to accomplish your goal, the reason your function does not work is because of your else { break; } statement.

break terminates the loop so unless the very first character is a ., then the loop will exit immediately after the first iteration. When you want to increment the loop, the correct keyword is continue although it is unnecessary in this case because all of the logic is housed inside of the if statement. Since there is no other logic to avoid, you should delete the else statement.

Related