Search code examples
javafor-loopif-statementbreakcontinue

How do I exit out from an if-statement in a for loop?


I want the program to run the if statement for the first iteration of the for loop, and then ignore it for the rest of the iterations. How do I do that? Continue and break didn't work either and led to a wacky output. The program is meant to take the first letter of each word in a string inputted and then form a word with those letters.

import java.util.Scanner;
class First_letter
{
    public static void main()
    {
        System.out.println("\f"); // clearing screen
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter a sentence");
        String s = sc.nextLine();
        String S = s.toUpperCase();
        String NS = "";
        char c = Character.MIN_VALUE;
        for (int i = 0; i < S.length(); i++)
        {
            if( i == 0 && Character.isLetter(S.charAt(0)))
            {
                NS = NS + S.charAt(0);
            }
            if (S.charAt(i) == ' ')
            {
                if (Character.isLetter(S.charAt(i+1)) == true)
                {
                    c = S.charAt(i);
                    NS = NS + c;
                }
            }
        }
        System.out.println("The word formed from the first letter of all the words in the sentence is "+NS);
    }
}

Solution

  • Assuming I understand your intent:

    If you only want code to execute for the first loop iteration, there's no reason for that code to be in the loop.

        if (S.length() != 0 && Character.isLetter(S.charAt(0)))
        {
           NS = NS + S.charAt(0);
        }
        for (int i = 0; i < S.length(); i++)
        {
            if (S.charAt(i) == ' ')
            {
                if (Character.isLetter(S.charAt(i+1)) == true)
                {
                    c = S.charAt(i);
                    NS = NS + c;
                }
            }
        }
    

    Note length check before accessing the 0'the character.

    For clarity, the two 'ifs' inside the loop can be combined into one, using the '&&' logical operator, but I left that part unchanged.