2014-01-16 102 views
0

我目前正在为类进行赋值,我想知道如何在字符串输入中找到一个整数。到目前为止,我已经创建了一种退出循环的方式。请不要给我代码只是给我一些想法。请记住,我对Java很新,所以请耐心等待。谢谢。 编辑:我忘了提及字符串输入应该像“woah123”,它应该只找到“123”部分。对不起在字符串内搜索一个int用户输入

import java.util.Scanner; 

public class DoubleTheInt 
{ 
    public static void main(String[] args) 
    { 
     int EXIT = 0; 
     while(EXIT == 0) 
     { 
      Scanner kbReader = new Scanner(System.in); 
      System.out.println("What is your sentence?"); 
      String sentence = kbReader.next(); 
      if(sentence.equalsIgnoreCase("exit")) 
      { 
       break; 
      }   
     } 
    } 
} 
+0

你的意思是,如果字符串是' “abc123efg”'程序应该找到'123'? – Christian

+0

你可以使用正则表达式或遍历字符串的每个索引,并检查它是否是一个数字。 – SudoRahul

+0

对不起,我没有澄清 编辑:不幸的是,我还没有学过正则表达式,所以我不知道如何使用 – user3059540

回答

1

这里是你做了什么......

Replace all non numeric characters with empty string using \\D and String.replaceAll function 
Parse your string (after replacing) as integer using Integer.parseInt() 

基督教的评论后编辑:

replaceAll() function replaces occurances of particular String (Regex is first argument) with that of the second argument String.. 
\\D is used to select everything except the numbers in the String. So, the above 2 lines combined will give "1234" if your String is "asas1234" . 

Now , Integer.parseInt is used to convert a String to integer.. It takes a String as argument and returns an Integer. 
+0

downvote是完整的答案? – TheLostMind

+0

不知道为什么downvote,我认为这很聪明。 – csmckelvey

+0

看看[this](http://meta.stackexchange.com/questions/148272/is-there-any-benefit-to-allowing-code-only-answers-while-blocking-code-only-ques ) – Christian

0

既然你不是在要求的代码,我给你一些建议。在字符串的方法

  1. 使用正则表达式来查找号码,并删除所有非 数字。

  2. 将字符串解析为整数。

2

为了学习目的,你可以做的是遍历整个字符串,并只检查数字。在这种情况下,您还将学习如何在字符串中检查char-by-char,如果将来您可能会要求这样也会得到该字符串的数字。希望解决您的问题。

+0

它就像重塑轮子.. – TheLostMind

+2

@TheLostMind:他是Java的新手,想要学习,考虑到答案是给出的。 – Mayur

+0

你..你可能是对的... – TheLostMind

0

除非你的任务“是”是一个正则表达式的任务,我建议你做它的非正则表达式的方式。即通过逐字符读取并检查整数或读取字符串并转换为字符数组和进程。

我不知道你的老师想让你做的,但有两个ways-

  1. 读逐个字符和过滤通过他们的ASCII码的数字。使用BuffferedReader从标准输入读取。并使用read()的方法。通过实验找出数字的ASCII代码范围。

  2. 一次读取整个字符串(使用Scanner或BufferedReader),看看您可以从String API中执行哪些操作(如可用于字符串的方法)。

0

使用Regular Expression:\ d +

String value = "abc123"; 
Pattern p = Pattern.compile("(\\d+)"); 
Matcher m = p.matcher(value); 
int i = Integer.valueOf(m.group(1)); 
System.out.println(i); 

输出

相关问题