0

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

3rd Nov 2022, 10:48 PM
FERUZ
2 ответов
+ 1
if you wish set data to null, do it after catch } catch (Exception excpt) { data = null; System.out.println(excpt.getMessage() ); } but better is throw IllegalArgumentException without try. And optionally catch it in the main() like api user programmer for friendly result on screen api throws Exceptions fast
4th Nov 2022, 2:31 AM
zemiak
0
Thank you zemiak! I will try your approach
4th Nov 2022, 8:46 PM
FERUZ