Java try/catch,catch不';不回答

Java try/catch,catch不';不回答,java,Java,此方法必须检查字符串中是否有数字,否则应在控制台中显示文本“不是数字” 但事实并非如此;请帮我查一下 public static int[] findNumbers(String text){ String[]str=text.split(" "); int count =0; for (String s:str){ if (isNumeric(s)) count++; } int[] numbers= new int[count];

此方法必须检查字符串中是否有数字,否则应在控制台中显示文本“不是数字” 但事实并非如此;请帮我查一下

public static int[] findNumbers(String text){
    String[]str=text.split(" ");
    int count =0;
    for (String s:str){
        if (isNumeric(s)) count++;
    }

    int[] numbers= new int[count];

    int index=0;
    try {
        for (String s:str){
            if (isNumeric(s)) numbers[index]=Integer.parseInt(s);
        }
        return numbers;

    }catch (Exception e){
        System.out.println("not a number");
    }
    return numbers;
}

private static boolean isNumeric(String text){
    if (text==null) return false;
    char[] chars=text.toCharArray();
    for (char ch:chars){
        if (!Character.isDigit(ch)) return false;
    }
    return true;
}

}

在isNumeric中添加一个else:

if (isNumeric(s)) {
    numbers[index]=Integer.parseInt(s);
} else {
    System.out.println("not a number");
}

更改catch中的错误消息。它可能仍然会被调用,比如当字符串太大而变成整数时。

尝试此实现,它避免自己实现
isNumeric
,并返回一个列表而不是数组,因为
数字的长度不固定

List number=new ArrayList();
for(字符串s:str){
试一试{
添加(整数.valueOf(s));
}捕获(数字格式){
System.out.println(s+“不是数字”);
}
}

您可以按如下方式减少代码:

public static List<Integer> findNumbers(String text) {
    String[] str = text.split(" ");
    List<Integer> numbers = new ArrayList<Integer>();
    for (String s : str) {
        try {
            numbers.add(Integer.parseInt(s));
        } catch (NumberFormatException e) {
            System.out.println(s+" is not an integer");
        }
    }
    return numbers;
}
公共静态列表findNumber(字符串文本){
字符串[]str=text.split(“”);
列表编号=新的ArrayList();
for(字符串s:str){
试一试{
add(Integer.parseInt(s));
}捕获(数字格式){
System.out.println(s+“不是整数”);
}
}
返回号码;
}

如果字符串是数字,则只调用
parseInt
,如果字符串是数字,
parseInt
可能不会引发错误。try and catch用于错误处理。我想你需要一个if语句。您的try-catch使用有效代码执行,如果没有,无论出于何种原因,您都会使用“常规异常”捕获它