Question: Using Java, write a program to calculate available credit. The program must prompt the user for their credit limit and the amount owing. Based on the user input, print the available credit limit.
Warning!
Please import selected Java packages or use import java.util.*;. Do not copy my code as per copyright and plagiarism regulations. This Java code is provided as it is for demonstration purposes.Solution 1: Can you determine any improvements without looking at the Solution 2?
public class AvailableCredit { public static void main (String [] args) { // Create a Scanner object attached to the keyboard Scanner in = new Scanner (System.in); // Reading limit System.out.print("Enter the limit: $"); int limit = in.nextInt(); // Reading the owing System.out.print("Enter the amount owing: $"); int owing = in.nextInt(); // Available credit limit int available = limit - owing; System.out.print("The available credit = $" + available); } }
Solution 2: This is a more refined solution that achieve the same results as the Solution 1. The variables limit, owing and available are defined at the top eliminating the need to define the variables as we go down the code. The integer variable int is replaced by double, which will allow inputs with decimal places (eg. 940.5, 119.15, etc).
public class AvailableCredit { public static void main (String [] args) { // Declare variable double limit, owing, available; Scanner m = new Scanner (System.in); // Requesting credit limit System.out.print("Enter the limit: $"); limit = m.nextDouble(); // Requesting the owing System.out.print("Enter the amount owing: $"); owing = m.nextDouble(); // Available credit limit available = limit - owing; System.out.print("The available credit = $" + available); } }
Output:
Enter the limit: $55.5
Enter the amount owing: $995.5
The available credit = $-940.0
User inputs are in italics are user entered values.
The public class AvailableCredit and variable names are arbitrary. This is to be expected in any programming language.