0

我正在使用命令行参数制作这个小程序,我已经完成了 90% 的工作。但我试图允许用户输入非数值以及..

用户输入/输出示例

输入:

$ java d1 4eb:16 10110110:2 407:8 2048:10

输出:

4eb base 16 is 1259 base 10 10110110 base 2 is 182 base 10 407 base 8 is 263 base 10 2048 base 10 is 2048 base 10

我唯一的问题是第一个输入,因为它有字母并且它给了我一个数字异常错误。任何帮助都会很棒,我更愿意在正确的方向上提供帮助,而不仅仅是答案。谢谢!

public class homework{
    public static void main (String[] args){
        int answer1=0,check1=0,check2=0,x=0, val=0,rad=0;   //holds integer values user gives and check for : handler, answer etc
        do{   //will continue to loop if no : inputted
        for (x=0;x<args.length;x++){

                check1=args[x].indexOf(":");        //checks input1 for the :
                if(check1==-1){System.out.println("No Colon Found in "+args[x]+".");check1=0;}
                else{
                    String numbers [] = args[x].split(":");     //splits the string at :
                    val = Integer.parseInt(numbers[0]);   //parses [0] to int and assigns to val
                    rad = Integer.parseInt(numbers[1]);     //parses [1] to int and assigns to rad
                    if(val==0||rad==0){System.out.println("The argument "+args[x]+" could not be converted.");check2=0;}
                    else{
                    for (int i = 0; val > Math.pow(rad, i); i++){
                        int digit = (val / (int) Math.pow(10, i)) % 10;
                        int digitValue = (int) (digit * Math.pow(rad, i));
                        answer1 += digitValue;}
                        answer1 = Integer.parseInt(numbers[0], rad);   //finds the answer in base10.
                        System.out.println(val+" base "+rad+" is "+answer1+" base 10.");  //gives user the results
            }}}}while(check1==-1);  }}  //if user forgot : loop
4

2 回答 2

1

根据要求,这里有一些提示。

这里出现了异常:

val = Integer.parseInt(numbers[0]);

您总是在解析冒号之前的数字,就好像它是以 10 为底的一样,即使它不是。

此外,for循环的目的使我难以理解。使用正确的基数解析数字后,以 10 为基数将其打印出来非常简单。

于 2011-09-15T18:59:13.500 回答
1

首次调用 parseInt 时需要指定基数。例如,如果您正在解析一个十六进制数字,则需要指定:

val = Integer.parseInt(numbers[0], 16)

您收到此异常是因为您尝试解析以 10 为底的十六进制数。

也许你应该让 base 成为另一个命令行参数。我假设它是第一个命令行参数。然后你可以运行:

int base = Integer.parseInt(args[0])
val = Integer.parseInt(number[0], base)
于 2011-09-15T19:02:45.140 回答