java输入一个字符串,从左到右取出其中的数字组成一个整数,输出该整数减去123的值?

java输入一个字符串,从左到右取出其中的数字组成一个整数,输出该整数减去123的值?

1.使用正则表达式做,注意Java使用正则表达式,必须导入java.util.regex.Matcher和java.util.regex.Pattern包
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class test{
public static void main(String[] args) {
String str,temp;
str = new Scanner(System.in).nextLine();
temp = Pattern.compile("[^0-9]").matcher(str).replaceAll("");
int result = Integer.parseInt(temp) - 123;
System.out.println(result);
}
}
2.使用字符串的substring方法做
import java.util.Scanner;
public class test{
public static void main(String[] args) {

String str,temp="";
str = new Scanner(System.in).nextLine();
for (int i = 0; i < str.length(); i++) {
if ((int)str.substring(i, i+1).charAt(0)>=48 && (int)str.substring(i, i+1).charAt(0)<=57) {
temp+=str.substring(i, i+1);
}
}
int result = Integer.parseInt(temp) - 123;
System.out.println(result);
}
}
温馨提示:答案为网友推荐,仅供参考

相关了解……

你可能感兴趣的内容

本站内容来自于网友发表,不代表本站立场,仅表示其个人看法,不对其真实性、正确性、有效性作任何的担保
相关事宜请发邮件给我们
© 非常风气网