1

I'm trying to copy only the numbers from an addition series say 45+45+45 The code works just fine until the moment it encounters the last 45 and all I get displayed are two 45's where I wanted all the three of them.I'd like suggestions for what I haven't done which would give me the exact output.Here's my code

InputStreamReader read = new InputStreamReader(System.in);
   BufferedReader in = new BufferedReader(read);
   String str = "", st;
   System.out.println("Enter Number");
   st = in.readLine();
   int l = st.length();
   int c = 0;
   String arr[] = new String[20];
   for(int i = 0; i < l; i++)
   {
       char chr = st.charAt(i);
       if(chr == '+')
       {
           arr[c++] = str;
           str = "";
       }
       else
       {
           str += chr;
       }
   }
   for(int i = 0; i < c; i++)
   {
       System.out.println(arr[i]);
   }
}
coolhack7
  • 1,204
  • 16
  • 35

1 Answers1

3

Take a look in your code. You are only adding the content into the array after you read an +. As the last '45' number has no remaining + left, it is not added into your array.

If this is not a homework, the best solutions is to use split() as suggested in the comments. In other case, I would recommend you to store the last content of the str when the loop is over. It contains the remaining characters left.

It is an easy code and I am sure that you can figure it out.

King Midas
  • 1,442
  • 4
  • 29
  • 50
  • That is exactly what has taken away my sleep.I cant think of a logic to get all those numbers into the array.How do I get the last one? – coolhack7 Feb 12 '18 at 12:57
  • Why don't you use the split() Method? arr = st.split("+"); – TheNewby Feb 12 '18 at 13:03
  • It did occur to me once but in the event of the series having different operators,would it work then? – coolhack7 Feb 12 '18 at 13:07
  • 1
    No it wouldn't. This example will split the string with the seperator "+" and nothing else. Maybe this will help you. https://stackoverflow.com/questions/3422673/evaluating-a-math-expression-given-in-string-form – TheNewby Feb 12 '18 at 13:14