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);
}
}
You are using the
indexOfmethod to get the index of a character. If it does not exist in the string, theindexOfreturns a-1. That's how you get the negative values.Consider
345as the input. You are iterating (i) from0to2(s.length() - 1is 2).Hint: You can use instead this:
No need to deduct
1from 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 no0in the string, it will return-1.