我正在使用命令行参数制作这个小程序,我已经完成了 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