如何解决检查字符串是否包含接受参数 String
我是一名学生,对 Java 有点陌生。对于我的家庭作业,我必须:
这个词必须:
- 以大写字母开头
- 以数字结尾
- 包含“cse”一词。
我被要求在一些执行特定任务的代码作业中创建一个方法,该方法应该检查所有必需的条件,方法的名称应该是 countTest
并且 它接受字符串作为一个参数。
输出格式
System.out.println("There as a total number of words " + count + " and
the ones that fulfill the condition are: " + condition);
问题是,我不知道如何创建方法或构造函数或调用其中的所有 3 个方法的任何调用,然后将该特定方法连接到主方法! 我希望你们能理解我是新手,提前谢谢你!
public class D6_6 {
public static void main(String[]args){
Scanner sc = new Scanner(system.in);
System.out.println("Type a number that is at least 7");
int number = sc.nextInt();
int count = 0;
int condition = 0;
do{
if(number<7){
System.out.println("You should type a number that is at least 7 or higher");
number = sc.nextInt();
}
}
while(number<7);
sc.nextLine();
String str;
for(int i =0; i<number; i++){
System.out.println("Type a word");
str = sc.nextLine();
count++;
}
}
public boolean countTest(String str) {
}```
解决方法
-
要检查单词是否以大写开头: 您可以先通过
str.charAt(0)
选择要检查的字符来完成此操作。这将返回一个字符,它是输入str
的第一个字母。
要检查此字符是否为大写字母,您可以轻松使用char.isUppercase()
。这将返回一个布尔值。如果您将char
的字符放入,您必须将str.charAt(0)
替换为变量的名称。 -
检查最后一个字符是否为数字: 您可以通过先按
str.charAt(str.length()-1)
选择最后一个字符来再次执行此操作,其中string.length-1
是最后一个字符的编号。
要检查此字符是否为数字,可以使用 ascii 表。每个角色都有自己的编号。所以如果你想检查你的字符是否在 0 到 9 之间,你可以使用char >= 48 || char <= 57
(在 ascii 表中查找)。同样,char
是您将str.charAt(str.length()-1)
的字符放入的变量的名称。 -
检查单词是否包含“cse”: 有一个非常简单的方法:
str.contains("cse")
将返回一个布尔值,当单词中包含“cse”时为真,当单词不包含“cse”时为假。
我希望你现在清楚了!
,我想我做到了,非常感谢你们,我很感激!
public class D6_6 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Type a number that is at least 7");
int number = sc.nextInt();
int count = 0;
int condition = 0;
do {
if (number < 7) {
System.out.println("You should type a number that is at least 7 or higher");
number = sc.nextInt();
}
}
while (number < 7);
sc.nextLine();
String str;
for (int i = 0; i < number; i++) {
System.out.println("Type a word");
str = sc.nextLine();
count++;
if((countTest(str))){
condition++;
}
}
if(count == 0){
System.out.println("No words typed");
} else {
System.out.println("Total number of words typed: " + count + ",which fulfill the condition: "+ condition);
}
}
public static boolean countTest(String str) {
return Character.isUpperCase(str.charAt(0)) && str.charAt(str.length() - 1) >= 48 || str.charAt(str.length() - 1) <= 57 || str.contains("cse");
}
}```
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。