gpt4 book ai didi

java - 查找条目中的特定位置

转载 作者:行者123 更新时间:2023-12-01 11:06:09 29 4
gpt4 key购买 nike

你好,我对 java 很陌生,目前正在学习使用 java 的编程类(class)。我无法找到角色的具体位置。该条目应该全部是数字,如果有一个字母,它应该告诉该字母所在的位置。我也不能使用循环来完成这项任务。这是迄今为止我得到的最好结果,但只有当条目有 x 时才有效。我怎样才能让它显示字母表中任何字母的位置?如果我听起来很愚蠢,我很抱歉,但我对 Java 非常陌生。提前致谢。

String alphabet = "x";
if (!isbn.matches("[0-9]+")) {
System.out.println("You need to enter a numeric digit at position " + isbn.indexOf(alphabet));

最佳答案

翻转正则表达式以搜索无效字符:

String isbn = "978-3-16-148410-0";
Matcher m = Pattern.compile("[^0-9]").matcher(isbn);
if (m.find())
System.out.println("You need to enter a numeric digit at position " + m.start());

输出

You need to enter a numeric digit at position 3

改进的打印

System.out.printf("You need to enter a numeric digit at position %d%n  %s%n%" + (m.start() + 3) + "s%n", m.start(), isbn, "^");

输出

You need to enter a numeric digit at position 3
978-3-16-148410-0
^

关于java - 查找条目中的特定位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32929357/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com