Reputation: 1224
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]);
}
}
Upvotes: 1
Views: 54
Reputation: 1699
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.
Upvotes: 3