【问题标题】:Checking if the input starts with a number and ends with an Upper letter检查输入是否以数字开头并以大写字母结尾
【发布时间】:2020-05-07 22:32:44
【问题描述】:

我不知道为什么这不起作用,因为即使我键入一个以数字开头、包含“end”并以大写字母结尾的句子,它们的值仍然是 0。此外,这应该区分大小写。

if (sentence.startsWith("[0-9]") && sentence.contains("end") && (sentence.endsWith("[A-Z]"))) {
    y++;
}
System.out.println(y);

【问题讨论】:

  • 您能否提供示例输入
  • 这是我写的代码 // Scanner scan = new Scanner(System.in);整数编号=0; while (no4"); no = Integer.parseInt(scan.nextLine()); } scan.nextLine();串句;整数 y =0; for (int i=0; i
  • String.startsWith() 接受一个字符串,而不是一个模式。同样endsWith()。
  • @Jane 我的意思是像1endH 这样的示例输入,而不是验证输入是否结束的代码
  • 因为你想检查第一个字符,你可以使用Character.isDigit。此外,可以使用Character.isUpperCase 检查最后一个字符。请注意,这两种方法都遵循“数字”和“大写”的 Unicode 定义。

标签: java string methods java.util.scanner digits


【解决方案1】:

试试这个。由于他们的开销,我尽量避免使用regular expressions,除非它真的简化了任务。在这种情况下,有一些方法可以促进该过程。

另外,句子开头和结尾的空格会影响结果(即不被修剪)。


int lastIdx = sentence.length()-1;
if (Character.isDigit(sentence.charAt(0))
        && sentence.contains("end")  
        && Character.isUpperCase(sentence.charAt(lastIdx))) {
           y++;
}

【讨论】:

  • 您可以补充一点,这与 'digit' 和 'uppercase' 的 Unicode 定义相匹配,即拉丁语以外的其他脚本也可能有数字和大写。
【解决方案2】:

您的代码不起作用,因为String::startWith 在您使用正则表达式时没有将正则表达式作为参数。您需要使用String::matches,如下所示:

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        int no = 0;
        while (no < 4) {
            System.out.print("Type a number >4: ");
            no = Integer.parseInt(scan.nextLine());
        }
        String sentence;
        int y = 0;
        for (int i = 0; i < no; i++) {
            System.out.print("Enter a sentence: ");
            sentence = scan.nextLine();
            if (sentence.matches("[0-9]+.*end.*[\\p{javaUpperCase}]")) {
                y++;
            }
        }
        System.out.println(y);
    }
}

示例运行:

Type a number >4: 5
Enter a sentence: Hello world
Enter a sentence: 123 Hello World ends with LD
Enter a sentence: 123HelloendHH
Enter a sentence: Good morning
Enter a sentence: 123Good morning
2

【讨论】:

  • 如果您使用匹配项,我认为您不需要模式末尾的 $。
  • 你是对的。没有它也可以工作。我已经更新了。
  • 当我复制和粘贴你的课程时它可以工作,但是当我在我的代码上更改它时(你的 if 部分)它仍然显示 0。Idk 为什么,:///
  • @Jane - 我已根据您的代码更新了答案。如果有任何进一步的问题/疑问,请随时发表评论。
  • 我接受了它,因为它可以独立运行,这意味着我自己编写的一些代码是错误的,而不是你写的。所以你的答案有效。非常感谢
【解决方案3】:

查看此正则表达式(^[0-9]+)(end)([A-Z]+$) 以一个或多个数字开头并以一个或多个大写字符结尾

    if (sentence.matches("(^[0-9]+)(end)([A-Z]+$)")) {
        y++;
    }
    System.out.println(y);

【讨论】:

  • 句子中是否包含end这个词?
  • 如果不包含end,则导致条件为false
  • 是的,它包含结尾。当我仅使用“结束”条件尝试时,它可以工作(y 的值增加)但不适用于其他两个条件。
  • 编辑你的锅并添加输入示例
  • 匹配项不需要 ^ 和 $。
猜你喜欢
  • 2014-08-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-01-05
  • 1970-01-01
  • 2012-12-31
  • 2020-11-22
相关资源
最近更新 更多