Coding - Java
Phần 4: Coding của bài thi đầu vào bank T đỏ.
Question
Find the count of uppercase characters in the given string.
Note: Uppercase characters or capital letters are a typeface for larger characters.
For example a, b and c are lowercase. A, B and C are uppercase
Function Description: In the provided code snippet, implement the provided UpperCase(...) method to find the count of uppercase characters in the given string. You can write your code in the space below the phrase "WRITE YOUR LOGIC HERE".
There will be multiple test cases running, so the input and output should match exactly as provided.
The base output variable result is set to a default value of -404 which can be modified. Additionally, you can add or remove these output variables.
Sample
- input: PaSSworD
- Output: 4
import java.util.Scanner;
public class Main {
public static int upperCase(String s) {
// this is default OUTPUT: You can change it.
int result = -404;
// WRITE YOUR LOGIC HERE:
return result;
}
public static void main(String[] args) {
// INPUT [uncomment & modify if required]
Scanner sc = new Scanner(System.in);
String s = sc.nextLine();
// OUTPUT [uncomment * modify if required]
System.out.println(upperCase(s));
sc.close();
}
}
Trong Java, bạn có thể sử dụng phương thức tiện ích Character.isUpperCase(char) để thực hiện việc này một cách nhanh chóng.
public static int upperCase(String s) {
// Khởi tạo biến đếm bằng 0 thay vì -404
int result = 0;
// WRITE YOUR LOGIC HERE:
// Kiểm tra trường hợp chuỗi rỗng hoặc null
if (s == null || s.isEmpty()) {
return 0;
}
// Duyệt qua từng ký tự trong chuỗi
for (int i = 0; i < s.length(); i++) {
char ch = s.charAt(i);
// Kiểm tra nếu ký tự là chữ hoa
if (Character.isUpperCase(ch)) {
result++;
}
}
return result;
}
All rights reserved