Well, first you needed to implement the isBinary() method correctly.
Second, the error you receive is because of the for-loop condition
"counter<=length", should be counter<length; since the index of the String starts at 0 the maximum index would be length-1.
Third, (2^counter) is not what you want to do here; it is the bitwise exclusive OR operator. What you want to do is use the Math.pow(base,power) method.
So here is the changed code try to understand and learn:
CODE
import java.util.Scanner;
import java.lang.Math;
public class BinaryToDecimal {
public static boolean isBinary(String input) {
boolean check = true;
for(int i=0; i < input.length(); i++){
if(input.charAt(i) == '0' || input.charAt(i) == '1'){
continue;
}
else {
check = false;
break;
}
}
return check;
}
public static void main(String[] args){
Scanner keyboard = new Scanner(System.in);
String binary;
int binValue = 0;
int ones = 0;
boolean done=false;
System.out.print("Enter a valid binary number:");
binary = keyboard.next();
//find length of number
int length = binary.length();
do {//do while loop for repeating if the input is incorrect
if(isBinary(binary)) {//using isBinary(String input) method
int exp = length-1;//exponent for calculations
for (int counter = 0; counter<length; counter++) {//changed condition
//Calculations for each one in the binary number
if (binary.charAt(counter) == '1') {
binValue = binValue +(int) (Math.pow(2.0, exp));//using pow method
//Number of ones in the number
ones = ones + 1;
}
//Separate calculations for 0's
else {
ones = ones + 0;
}
exp--;
}
done = true;
}
//re-prompt if the number contains anything other than ones and zeros (Invalid binary number)
else {
System.out.println(binary + " is not a valid binary number.");
System.out.print("Enter a valid binary number:");
binary = keyboard.next();
}
}while(!done);
System.out.println("Your number " + binary + " contains " + ones + "one(s)");
System.out.println("The decimal value of " + binary + "is: " + binValue);
}
}