Home > Mobile >  Number base conversion returning (-ve) value
Number base conversion returning (-ve) value

Time:10-25

I am self-learning Java programming and I was trying to do some number conversion from base 10 to any base, but I keep getting a negative value with the code below

import java.lang.Math;
import java.util.Scanner;

public class NumberSystemConversion {
    public static void main(String [] args) {
        System.out.println("Enter the  source base of the integer");
        Scanner sc = new Scanner(System.in);
        int sBase = sc.nextInt();
        System.out.println("Enter the destination base of the integer");
        int dBase = sc.nextInt();
        System.out.println("Enter the integer");
        String s1 = sc.next();

        //int len = s1.length();
        int decNumber = 0;
        for (int i =0; i <= s1.length()-1;  i  ) {
            decNumber  = s1.indexOf(i)*Math.pow(sBase,i);
        }
        System.out.println(decNumber);
    }
}

CodePudding user response:

You are using the indexOf method to get the index of a character. If it does not exist in the string, the indexOf returns a -1. That's how you get the negative values.

Consider 345 as the input. You are iterating (i) from 0 to 2 (s.length() - 1 is 2).

Hint: You can use instead this:

for (int i = 0; i < s.length(); i  ) 

No need to deduct 1 from the length and check whether it is less or equal.

Then you check the s1.indexOf(i). In the first iteration, s1.indexOf(0) is checked, and since there is no 0 in the string, it will return -1.

CodePudding user response:

You are using the indexOf() method to get the index of a character. But it is totally unsuitable in your context. To iterate over the characters of a String, use charAt() or even better codePointAt() like so:

for (int i = 0; i < s.length(); i  )  {
    System.out.println( s.codePointAt(i) );
}

Once there, you will have to convert the character's unicode codepoint into the number you want to calculate with. This table may help: https://www.unicode.org/charts/PDF/U0000.pdf

  • Related