Ok so basically this code finds all the numbers in a string then prints out how many digits they have...
The code works fine but if the string has a number at the end it prints out "StringIndexOutOfBoundsException" and as u see I threw that exception in the class but with no use... I don't understand why it gives me that message every time there is a number at the end of the string...
//Number Finder
import java.io.*; public class pas4{ public static void main (String args []) throws IOException, StringIndexOutOfBoundsException{ InputStreamReader instream = new InputStreamReader(System.in); BufferedReader br = new BufferedReader(instream); System.out.println("Please insert a passage"); String psg = br.readLine(); int i = 0; String tmp = ""; while (i < psg.length()){ while (((psg.charAt(i)) >= 48) && ((psg.charAt(i)) <= 57) && (i < psg.length())){ tmp = tmp + psg.charAt(i); i = i + 1; } if (tmp.equals("")){ i = i + 1; }else{ int z = Integer.parseInt(tmp); int digits = 0; while (z != 0){ z = z / 10; digits = digits + 1; } System.out.print(tmp + " has "); System.out.println(digits + " digits "); tmp = ""; i = i + 1; } } } }
Example input: I'll live till 42
Output: Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 17
at java.lang.String.charAt(String.java:686)
at pas4.main(pas4.java:34)