简体   繁体   中英

string to char to string to int

Basically, what this code does is getting a number in any length from the user and sends it back to the user in a digit per digit form plus the sum of all the digits on the given number(eg 1234= 1, 2, 3, 4. sum=10). However, I can't make it work on a negative number.

    Scanner s= new Scanner(System.in);

    String num= s.nextLine();

    char arr[]= new char[num.length()];
    int numsarray[]= new int[num.length()];
    String number[]= new String[num.length()];
    int sum=0;

    for(int i=0; i<num.length();i++)
    {
        arr[i]=num.charAt(i);
        System.out.println(arr[i]);

        number[i]=Character.toString(arr[i]);

        numsarray[i]=Integer.parseInt(number[i]);
    }

    for(int i=0;i<num.length();i++)
    {   
        sum+=numsarray[i];
    }
    System.out.println("Sum:"+sum);

Any reason you do not check first whether the number is less then 0 or not? You could then use abs to make it positive and run it through your function. Takes away the hassle to deal with the hyphen at arr[0]. Of course you should have some bool to store the sign :-)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM