1

I'm encountering an issue while attempting to utilize the substring method to locate a specific character within a string variable. Currently, I have set up a for loop to iterate over the length of a string variable named name. Inside this loop, I use the substring method within an if statement to search for a particular character, denoted by a ".".

However, despite my efforts, I've been unable to achieve the desired outcome. I would greatly appreciate any assistance in resolving this issue. Here's the relevant portion of my code:

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 cannot 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 restart the application
        if (opt1.equals("1")) {
            System.out.println("menu launch");
        } else {
            System.exit(0);
        }
    } else {
        break;
    } 
}

I would appreciate any insights into why my approach isn't working as expected and how I might rectify it. Thank you in advance for your assistance!

2 Answers 2

3

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...
Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.