Here I have a string and an array

String s[] = new String[5]; int num[] = new int [5]; 

How to convert or write a string to an integer array without using Integer.parseInt (s)?

1 answer 1

Is this a learning task? Why such a strange restriction? Use new Integer(s) .


If you really pervert, you can try to parse manually:

 long result = 0; boolean negative = false; int i = 0, len = s.length(); if (len > 0 && s.charAt[0] == '-') { negative = true; i = 1; } for (; i < len; i++) { char c = s.charAt(i); int digit = (int)c - (int)'0'; if (digit < 0 || digit > 9) throw new IllegalArgumentException("Not a valid digit: '" + c + "'"); result = 10 * result + c; if (result > Integer.MAX_VALUE + 1) // подумайте, почему именно так throw new IllegalArgumentException("Integer overflow"); } if (negative) result = -result; if (result > Integer.MAX_VALUE) throw new IllegalArgumentException("Integer overflow"); return (int)result; 
  • I am trying to learn java on my own, so to some extent this is a learning task. And there is no limit, I just became curious. - inham130
  • Well, if within the framework of curiosity, then you can come up with the following solution, worthy of the best sons from the country of elephants and tea: int crazy_int; if ("1" .equals ("" + 1)) crazy_int = 1; - Chavez