In: Computer Science
Write a Java method that takes an input string and computes the income minus the expenses. The income components are indicated by numbers; while the expenses from your spending are numbers starting with a minus sign '-'.
The input string may contain lowercase and uppercase letters, as well as other characters.
Note that Character.isDigit(char) tests if a char is one of the chars '0', '1', ..., '9'. Also recall that Integer.parseInt(string) converts a string to an int.
Test cases : calcNetIncome("salary 15000yuan bonus2000 rent -1000Y") → 16000 calcNetIncome("25000 gross income, -200 water, electricity:-300") → 24500
/* Java class */
public class Main{
/* This function calculates the net income */
/* Param: An alphanumeric string <s>*/
/* Return: An integer number <net>, denoting net income */
public int calcNetIncome(String s){
/* declare variables */
int len, i, net = 0;
String num = "";
/* find length of string */
len = s.length();
/* check for each character */
for(i = 0; i <len; i++){
/* if characters are digits or -, concatenate */
if (((int)s.charAt(i) >= 48 && (int)s.charAt(i) <= 57) || (int)s.charAt(i) == 45){
num += s.charAt(i);
}
else{
/* if a string of digits and - found */
/* convert to integer and add to sum */
if(num.length() > 0){
net += Integer.parseInt(num);
/* make string empty */
num = "";
}
}
}
/* End of string reached while reading an integer */
if(num.length() > 0)
net += Integer.parseInt(num);
/* return net income */
return net;
}
public static void main(String[] args){
/* declare object */
Main obj = new Main();
/* declare variables */
int result;
/* call the function */
result = obj.calcNetIncome("25000 gross income, -200 water, electricity:-300");
/* display the result */
System.out.print("Net income: "+result);
}
}
___________________________________________________________________
___________________________________________________________________
Net income: 24500
___________________________________________________________________
Note: If you have
queries or confusion regarding this question, please leave a
comment. I would be happy to help you. If you find it to be useful,
please upvote.