簡體   English   中英

如何退出 for 循環中的 if 語句?

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

我希望程序為 for 循環的第一次迭代運行 if 語句,然后在迭代的 rest 中忽略它。 我怎么做? 繼續和中斷也不起作用,並導致了一個古怪的 output。 該程序旨在獲取輸入字符串中每個單詞的第一個字母,然后用這些字母組成一個單詞。

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);
    }
}

假設我理解您的意圖:

如果您只希望代碼在第一次循環迭代中執行,則沒有理由將該代碼置於循環中。

    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;
            }
        }
    }

在訪問 0' 字符之前注意長度檢查。

為清楚起見,循環內的兩個“if”可以使用“&&”邏輯運算符合並為一個,但我保持該部分不變。

如果我正確理解你的問題,你想從句子中每個單詞的第一個字母創建一個單詞。 如果這是真的,那么以下應該解決它。 讓我們保持簡單。

  1. 把句子分成單詞。
  2. 從每個單詞中取出第一個字符。
  3. 將其更改為大寫。
  4. 最后,加入每個單詞的結果。
public static void main(String[] args) {
        System.out.println("\f"); // clearing screen
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter a sentence: ");
        System.out.println("The word formed from the first letter of all the words in the sentence is "
                + Joiner.on("")
                .join(Arrays.stream(sc.nextLine().split("\\s+"))
                        .filter(StringUtils::isNotBlank)
                        .map(w -> w.charAt(0))
                        .map(Character::toUpperCase).toList()
                )
        );
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM