I am making a program that takes a five digit binary code entered by the user and displays the value of that code. I have no problem determining if the user enters five digits or not or how to calculate the answer so those aspects aren't included in the code here. The problem I'm having is
determining if the user's input is indeed binary. Below is a test I was running to help me conceptualize how to do this. I wanted to use the counter "nobin" to help me determine if the numbers entered are binary or not. The idea is that if the user enters a value that is not 0 or 1 then 1 is added to nobin. Later I would have code that would check to see if nobin is greater than 0. If it is then ,obviously, something other than a 1 or a 0 was entered and thus direct the user to enter a valid binary code. When I run this program , however, nobin always executes even when only ones and zeros are entered. I hope some of you brilliant people can enlighten me as to why this is. Thanks!
import java.util.Scanner; public class Binary { public static void main (String [] args){ Scanner input= new Scanner(System.in); System.out.println("Enter a five digit binary number");//prompts user to enter # String user= input.nextLine();// sets user input to string "user" String delims=""; //sets the delimiter for string split String str[]=user.split(delims); //splits the number input into an array int count=0;//counter for while loop int nobin=0; //counter to determine if character //other than a one or zero is entered while (count<user.length()){//loops through each character of user input to //determine if input contains characters other than a // one or a zero. count++; if (str[count]!="0") { if (str[count]!="1") nobin++; } } System.out.println(nobin); } }