2015-10-04 42 views
0

你好,对Java很新,我现在正在使用java对编程类进行介绍。我无法找到角色的具体位置。假设条目是全部数字,如果有字母,则假设该字母位于什么位置。我也不能使用循环来完成这项任务。这是迄今为止我得到的最好结果,但它只有在条目有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)); 
+0

至少,你为什么不先写一个算法。稍后,您可以尝试编写代码。如果失败,你甚至试图找出失败的原因吗? – Pawan

回答

0

有几种方法可以解决这个问题,但我不能保证这是最好的,但是这里是解决方案的大纲。我将离开实施作为练习,所以我不做你的功课;-)

首先,拿出一个正则表达式来贪婪地匹配数字(就像你已经有的)并且使用Java的Pattern类。

然后,使用Matcher及其replaceFirst方法用空字符串替换匹配的模式。什么结果将是一个字符串,它以第一个非数字字符开始,直到输入字符串结束。

然后,您可以通过查看“不匹配的尾部”是否为空来查看输入是否有效。

最后,如果输入无效,则使用输入字符串的索引和这个“不匹配的尾部”来告诉用户第一个坏字符在哪里。

下面是一些“剩下的练习”的轮廓。每一个“练习”都是一行一行。您应该能够在PatternMatcherString的链接文档中找到所需的全部内容。

public static void main(String[] args){ 
    String myStr = "0123f5"; 
    //Excercise: compile a greedy number matching regex 

    //Excercise: get an instance of a matcher for this regex and the input string 

    //replace the first match in input string to greedy 
    //number-pattern with empty string 
    String mismatchedTail = m.replaceFirst(""); 
    if(!mismatchedTail.equals("")){   
     System.out.println("Must enter numeric value at index: "/*Excercise: use index of, the mismatch tail, and input to get the first invalid index*/)); 
    } else { 
     System.out.println("Good 2 go"); 
    } 
} 

结果当我填补了空白部分运行它:

Must enter numeric value at index: 4 
+0

感谢您的帮助,我非常感谢! – Moonshadow

1

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

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 
    ^
+0

这个问题显然是一项家庭作业。你会考虑更多的“让我帮你找出自己的东西”而不是“这是代码”的方法吗? – augray