In: Computer Science
Java question - How can the code below be modified to accept multi digit input.
String e = "1+9+8";
int r = e.charAt(0)-'0';
for (int i = 1; i < e.length(); i+=2){
if (e.charAt(i) == '+'){
r += e.charAt(i+1)-'0';
}
else{
r -= e.charAt(i+1)-'0';
}
The only built in String methods that can be used are lowercase(), length(), and charAt(). Arrays and parseInt() cannot be used.
So we want to know how we can get an answer if a string such as "123+45+678-...." is entered.
Modified java code :
public class MultiDigitInput {
public static void main(String[] args) {
// string
String e = "123+45+678-46";
// res store the result of
string
int res = 0;
// r store the numeric value of
whole numerical term
int r ;
for (int i = 0; i < e.length();
){
r = 0;
if (e.charAt(i)
== '+'){
i++;
// this loop will calculate the whole numerical
term
while(i < e.length() && e.charAt(i)
!= '+' && e.charAt(i) !='-' )
{
// every time add unit term
after multiplying by 10
r = r*10 +
e.charAt(i)-'0';
i++;
}
res += r;
}
else if
(e.charAt(i) == '-'){
i++;
while(i < e.length() && e.charAt(i)
!= '+' && e.charAt(i) !='-')
{
r = r*10 +
e.charAt(i)-'0';
i++;
}
res -= r;
}
// this will
calculate the first term
else {
while(i < e.length() && e.charAt(i)
!= '+' && e.charAt(i) !='-')
{
r = r*10 +
e.charAt(i)-'0';
i++;
}
res += r;
}
}
System.out.println(res);
}
}
Image for clear view :
output :
800
Hope you like it
Any Query? Comment Down!
I have written for you, Please up vote the answer as it encourage us to serve you Best !