没有弄错我的代码

时间:2015-10-25 18:21:27

标签: java computer-science

public class DigitRange {

public static void main(String[] args) {

    String numberstr = args[0];
    int numberint = Integer.parseInt(args[0]);
    int large=0;
    int small=0;
    System.out.println("range of " +numberint + " = "+ Range(numberstr,numberint,large,small));
}

public static int Range (String numberstr, int numberint,int large,int small){
    for(int i=1;i<=numberstr.length();i++){
        int digit = numberint % 10;
    numberint = numberint/10;
    large = Math.max(digit, large) ;
    small = Math.min(digit, small);
    }
    int range = large - small + 1;
    return range; //giving me 9
    }
}

我的代码出了什么问题?我从我的方法Range返回正确的值时遇到问题。当我应该返回值6时,我返回值9.我相信我有一个逻辑错误。

新问题: 公共类DigitRange {

public static void main(String[] args) {

    String numberstr = args[0];
    int numberint = Integer.parseInt(args[0]);
    int max=0;
    int min=9;
    System.out.println("range of " + numberstr + " = "+ Range(numberstr,numberint,max,min));
}
//finds and returns the range
public static int Range (String numberstr, int numberint,int max,int min){
    if(numberint<0){
        Math.abs(numberint);
        for(int i=1;i<=numberstr.length()-1;i++){
            int digit = numberint % 10;
            numberint = numberint/10;
            max = Math.max(digit, max) ;
            min = Math.min(digit, min);
        }
    }
    if(numberint>0){
        for(int i=1;i<=numberstr.length();i++){
            int digit = numberint % 10;
            numberint = numberint/10;
            max = Math.max(digit, max) ;
            min = Math.min(digit, min) ;
        }
        int range = max - min + 1;
        return range;
    }
}

}

如何才能将最大值和最小值超出if {}?

的范围

1 个答案:

答案 0 :(得分:2)

您正在寻找作为代码参数传递的数字中最小和最大的数字,差异+ 1是您的范围,对吗?

可能小的应该初始化为9。