簡體   English   中英

從用戶處獲取一個字符,並在 Java 中用戶給出的字符串中查找該字符的出現次數

[英]Get a character from the user and find the no of occurrences of the character in a string given by the user in Java

計算給定字符的出現次數。 編寫一個程序來接受用戶的一句話。 從用戶那里獲取一個字符並找到出現次數。

檢查給定的字符和單詞是否有效

如果單詞僅包含字母且不包含空格或任何特殊字符或數字,則該單詞是有效的。

如果字符是單獨的字母,則該字符是有效的。

示例輸入 1:輸入一個單詞:編程輸入一個字符:m

樣品 Output 1:

No of 'm' present in the given word is 2

示例輸入 2:輸入一個單詞:programming 輸入字符:s

樣品 Output 2:

The given character 's' not present in the given word.

示例輸入 3:輸入一個單詞:56 示例 Output 3:

Not a valid string

示例輸入 4:輸入單詞:Hello 輸入字符:6

樣品 Output 4:

Given character is not an alphabet

我的代碼:

import java.util.Scanner;

public class OccurrenceOfChar {

    public static void main(String[] args){
        Scanner sc=new Scanner(System.in);
        // Fill the code
        System.out.println("Enter a word:");
        String word=sc.nextLine();
        String words=word.toLowerCase();
        String find="";
        int len=word.length();
        int i, count=0, flag=0;
        for(i=0;i<len;i++)
        {
            char c=words.charAt(i);
            if(!(c>='a' && c<='z'))
            {
                System.out.println("Not a valid string");
                break;
            }
        }
        System.out.println("Enter the character:");
        find=sc.nextLine();
        if(!(find.length()==1) && (find.charAt(0)>='a' && (find.charAt(0)<='z')))
        {
            System.out.println("Given character is not an alphabet");
        }
        for(i=0;i<len;i++)
        {
            if(words.charAt(i)==find.charAt(0))
            {
                count++;
            }
        }
        if(count==0)
            System.out.println("The given character '"+find+"' not present in the given word.");
        else
            System.out.println("No of '"+find+"' present in the given word is "+count);
    }

   }

9 個測試用例中只有 2 個通過。 我無法指出邏輯中的錯誤。

測試 3:檢查不存在字符且單詞大寫時的邏輯

測試 4:檢查字符存在且單詞大寫時的邏輯

測試五:判斷單詞無效時的邏輯

測試6:檢查字符無效時的邏輯

測試7:檢查字符有2位時的邏輯

測試 8:當單詞沒有字母時檢查邏輯

測試9:檢查字符為特殊字符時的邏輯

*注意:所有測試用例的權重可能不同 +--------------------------------------------+ | 9 次測試運行/2 次測試通過 | +------------------------------+

將驗證字符串的邏輯移動到單獨的方法中,調用此方法來檢查給定的單詞是否為有效字符串

public boolean validateString(String str) {
      str = str.toLowerCase();
      char[] charArray = str.toCharArray();
      for (int i = 0; i < charArray.length; i++) {
         char ch = charArray[i];
         if (!(ch >= 'a' && ch <= 'z')) {
            return false;
        }
      }
      return true;
   }

暫無
暫無

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

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