java - Binary to decimal, error message -
java - Binary to decimal, error message -
i wrote programme convert binary number decimal number. when run programme binary number, programme give me decimal number error message.
my code:
public class ohad { public static void main(string[] args) { string bin = "10011"; int length = bin.length(); int j = 0; int sum = 0; if (length != 0) { (int i=0; < bin.length(); i++){ if (bin.charat(i) == '0' || bin.charat(i) == '1'){ (int t = (length - 1); t >= 0; t--){ string s = bin.charat(j) + ""; sum = (int)(sum + (integer.valueof(s)) * (math.pow(2, t))); j++; } system.out.println(sum); } else { system.out.println("illegal input."); } } } else { system.out.println("illegal input."); } } }
error message:
exception in thread "main" java.lang.stringindexoutofboundsexception: string index out of range: 5 @ java.lang.string.charat(string.java:646) @ ohad.main(ohad.java:15)
i think it's j index. should do?
what should do?
i utilize integer.parseint(string,int)
like
string bin = "10011"; system.out.println(integer.parseint(bin, 2));
output is
19
java for-loop binary decimal
Comments
Post a Comment