Question

In: Computer Science

To create a home budget, you want to find out your net income, which is your...

To create a home budget, you want to find out your net income, which is your income minus your expenses.

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

Solutions

Expert Solution

Java Method to create a home budget, which calculate net income from a given string by substracting total expenses from total incomes :

Main.java :

public class Main {
    
        /*
        Method to calculate netIncome from a given string.
        */
        public static double calculateNetIncome(String input) {
            //split input string into a single words and store words in String array.
            String[] words = input.split(" ");
            double totalIncomes = 0; //variable to hold totalIncomes.
            double totalExpenses = 0; //variable to hold totalExpenses.
            /*
            below for-each loop will execute for each word in array named words,
            */
            for(String word:words) { 
                /*
                check if word contain (-) symbol or not if yes then,
                this word should not be processed further to calculate total income
                because if word contain hyphen means this will considered as expense amount not as income.
                */
                if(!word.contains("-")) { // if word not contains - symbol then below block execute.
                    String income = "0"; // local variable to hold digit in current word if any.
                    /*
                    loop through each character of select word
                    */
                    for(int i=0;i<word.length();i++) {
                        //if character is a digit concatenate that digit with income varible.
                        if(Character.isDigit(word.charAt(i))) {
                            income +=word.charAt(i); // concatenate income varible.
                        }
                    }
                    /*
                    after above foreach terminate, add income and totalIncomes
                    since income variable if string we have to use Integer.parseInt() to convert it to Integer.
                    remember income variable will be either 0 (if current word doen't contain any digit) or any other numeric value.
                    */
                    totalIncomes = totalIncomes + Integer.parseInt(income);
                }
                /*
                check if word contain (-) symbol or if yes then,
                this word should be processed further to calculate total expenses
                because if word contain hyphen means this will considered as expense amount not as income.
                */
                else if(word.contains("-")) {
                     /*
                    loop through each character of select word
                    */
                    String expense = "0"; // local variable to hold digit in current word if any.
                    for(int i=0;i<word.length();i++) {
                        //if character is a digit concatenate that digit with expense varible.
                        if(Character.isDigit(word.charAt(i))) {
                            expense +=word.charAt(i);
                        }
                    }
                    /*
                    after above foreach terminate, add expense and totalExpenses
                    since expense variable if string we have to use Integer.parseInt() to convert it to Integer.
                    remember expense variable will be either 0 (if current word doen't contain any digit) or any other numeric value.
                    */
                    totalExpenses = totalExpenses + Integer.parseInt(expense);
                }
                /*
               from here program control will again go to for-each loop and 
               next available word in words array will be processed in same way as above
               */
            }
          /*
          after for-each loop terminates we have totalIncomes and totalExpenses calculated
          now substract totalExpenses from totalIncomes to get netIncome
          */
          
          double netIncome = totalIncomes - totalExpenses;
          
          /*
          instead of returning value from this function you may also print calculated value inside this function
          by making return type of this function as void instead of double according to need.
          */
          
          //return netIncome 
          return netIncome;
        }
        
        /*
        main method we will call calculateNetIncome() method in main method to see it's output 
        */
        public static void main(String[] args) {
            
            /*
            Creating tow test cases to test calculateNetIncome method.
            since we have created calculateNetIncome() return type as double,
            we need to store it's return value in double type variable.
            */
                double test1 = calculateNetIncome("salary 15000yuan bonus2000 rent -1000Y");
                double test2 = calculateNetIncome("25000 gross income, -200 water, electricity:-300");
                
                /*
                printing these two test result on console.
                */
                System.out.println("test1 result= "+test1);
                System.out.println("test2 result= "+test2);
            
        }
}

Sample output :

Please refer to the Screenshot of the code given below to understand indentation of the code :


Related Solutions

1. As an investor of a company, you want to find out your ROI provided by...
1. As an investor of a company, you want to find out your ROI provided by the company at the end of the current year.   Which of the following formulas would you use? Group of answer choices Net Income divided by the Average Asset of the company. Net Income divided by the Sales amount of the company. Net Income divided by the Equity amount of the company's ending Balance Sheet. Net Income divided by the average amount of the Total...
Which of the following would you find on the Income Statement? 1) Salary expense 2) Net...
Which of the following would you find on the Income Statement? 1) Salary expense 2) Net income 3) Capital stock 4) Income tax expense 5) Cash 6) Gain on sale of building 7) Loss on sale of investment 8) Sales 9) Dividends paid 10) Retained earnings
i want to create a weather api. which is pullling out information of all the cities(for...
i want to create a weather api. which is pullling out information of all the cities(for the whole world)  using their names or by their zipcode. and it should change the background image as the temperature is, cold, or hot, or mild etc. i need in help in making this weather api and also it can be in any language. please help me out
Wastewater Engineering: Find out which water treatment plant serves your home, draw a diagram including each...
Wastewater Engineering: Find out which water treatment plant serves your home, draw a diagram including each of the main components of the process. Describe the objective of each of the individual components.
You want to take out a $324,000 mortgage (home loan). The interest rate on the loan...
You want to take out a $324,000 mortgage (home loan). The interest rate on the loan is 5.3%, and the loan is for 30 years. Your monthly payments are $1,799.19. How much will still be owed after making payments for 10 years? $__________Round your answers to the nearest dollar. How much will still be owed after making payments for 15 years? $__________ Round your answers to the nearest dollar. How much will still be owed after making payments for 20...
You would like to purchase a home and are interested to find out how much you...
You would like to purchase a home and are interested to find out how much you can borrow. When your lender calculates your debt to income ratio, he determines that your maximum monthly payment can be no more than $4,349. You would like to have a 30 year fully- amortizing loan and the interest rate offered on such a loan is currently 3%. Given these constraints, what is the largest loan you can obtain? Round your answer to the nearest...
You have n numbers and you want to find a number x (out of the n)...
You have n numbers and you want to find a number x (out of the n) such that x is larger than the median. You can create an algorithim that takes time O(nlogn): sort the n numbers and then report any number that is larger than the element in position n2 of the sorted array. You can also create an algo in O(n) time, by finding the median in linear time and then doing a linear scan to find a...
You want to find out the percentage of community college students that own a pet. You...
You want to find out the percentage of community college students that own a pet. You decide to email five students in one of your classes and ask them if they own any pets. (a) What is the population in this example? (b) What is the sample? (c) What is the parameter of interest? (d) Suppose three of the five students tell you they own a pet, while the other two say they do not. i. Is this numerical or...
I want to find out which SPSS test I would use in this scenario: In this...
I want to find out which SPSS test I would use in this scenario: In this scenario a social psychologist working for an advertising firm was interested in whether the frequency of exposure to an advertisement would have an effect on the liking of that ad. He suggested that the more often a subject was exposed to an ad would have an effect on how much she / he would enjoy the ad. The study involved exposing a subject to...
Design your home network.  Experiment. Go beyond your home network. Design the network you want. Pick a...
Design your home network.  Experiment. Go beyond your home network. Design the network you want. Pick a networking problem from the internet and design the networking solution. Use lucidchart or vision.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT