How create array that only has 0 and 1 values?
Hi, I have a problem with my homework assignment. I need to populate array with digits that only 0 or 1. Any other digits, alphabetical characters and symbols should not be in the array and method should throw exception (Only digits or Only 0 or 1 values), in this case array should not be created. Could someone help me figure out the problem. Here is the code: public BinaryNumber(String str) { data = new int [str.length()]; try{ for(int i = 0; i < str.length(); i++){ char ch = str.charAt(i); if(!Character.isDigit(str.charAt(i))) { throw new Exception("Not digit!"); } if (ch == '0' || ch == '1') { data[i] = Character.getNumericValue(ch); } else { throw new Exception("Only 0 and 1 are allowed!"); } } }catch (Exception excpt) { System.out.println(excpt.getMessage()); } } public static void main(String [] args) { BinaryNumber data1 = new BinaryNumber("ggiuyuihk"); System.out.println(data1); } After running the program in main, I got message but also I've got array populated with same amount 0 values