/** (Hypothetical Annual Water Bill Summary Problem ) The water bills for the 12 months of a year by a water service subscriber is summarized as follows. Inputs: Water Meter Reading at the beginning of the year (i.e. January 1) Water Meter Readings at the end of each of the 12 months Payment Rates (Minimum Bill, price of water per cubic meter) Outputs: Cubic meters of water consumed for each month (monthly consumption) Amount paid for each month based on given rates (monthly payment) Average of monthly consumptions Average of monthly payments The month during which the amount of water consumed is highest The month during which the amount of water consumed is lowest Algorithm 1.Read the name of the water consumer (consumer). 2.Read The classification (cType) of the consumer such that the only valid values for cType is "commercial" or "residential". 3.Read water meter reading in cubic meters at the beginning of the year(previousR[0]). 4.For month 1 to 12 Read the water meter reading in cubic meters at the end of the month (presentR) such that presentR cannot be less than previousR. Store the value in an array. Compute the volume of water consumed for the month (consumption) by subtracting the previousR from presentR. Store the value in an array. Compute the amount due (amountDue) from the consumer based on the following rules If cType is residential and consumption <= 12, the amount due is 180.00 If cType is residential and consumption > 12, the amount due is 180.00 + (consumption – 12)*30.00 If cType is commercial and consumption <= 30, the amount due is 600.00 If cType is commercial and consumption > 30, the amount due is 600.00 + (consumption – 30)*50.00 Store the value in an array. 5. Determine the average of the monthly water consumptions. 6. Determine the average of the monthly payments. 7. Determine the month during which water consumed is highest. 8. Determine the month during which water consumed is least. 9. Print the name of the consumer. 10. Print the consumer type. 11. Print the water meter reading at the beginning of the year. 12. Print a table showing the 12 months, water meter readings at the end of each month, the amount paid due to the water consumption for each month. 13. Print the average of the monthly water consumptions. 14. Print the average of the monthly payments. 15. Print the month during which water consumption is highest. 16. Print the month during which water consumption is lowest. */ // You may modify the algorithm/program as you deem necessary import java.util.Scanner; public class LedesmaEuniceWaterBillAnnualSummary { public static void main(String[] args) { int[] presentReading= new int[12]; int[] startReading= new int[12]; Scanner scanner = new Scanner(System.in); String consumer=""; // to hold name of consumer char cType = 'x'; // to hold type of consumer int[] nCMUsed = new int[12]; /* to hold number of cubic meters of water used for 12 months */ int minCMResidential=12; /*to hold cut-off for minimum Bill for residential consumers */ double minBillResidential=180.00; // minimum bill for <= 12 Cubic Meters used float rateResidential =30.00F; //cost of 1 Cubic Meter above the min. consumption int minCMCommercial=30; /* to hold cut-off for minimum Bill for commercial consumers*/ double minBillCommercial=600.00; // minimum bill for <= 20Cubic Meters used float rateCommercial =50.00F; /*cost of 1 Cubic Meter above the min. consumption for commercial consumers*/ double[] amountDue= new double[12]; // to hold the amount paid for 12 months showIntroduction(); System.out.println(); System.out.println("------------------------------"); System.out.println("Welcome to the Water Bill Annual Summary program!"); System.out.println("This program will calculate and summarize your water bill for the year."); System.out.print("Enter the name of the water consumer: "); consumer = scanner.nextLine(); cType = readTypeOfConsumer(); startReading[0] = readStartReading(); for (int index=0; index < nCMUsed.length; index++){ presentReading[index] = readEndOfMonthReading(startReading[index], (index+1)); if (index < (nCMUsed.length - 1)) startReading[index+1] = presentReading[index]; nCMUsed[index] = presentReading[index] - startReading[index]; amountDue[index] = computeAmountDue(nCMUsed[index], cType, minCMResidential, minBillResidential, minCMCommercial, minBillCommercial, rateResidential, rateCommercial); } showSummary(consumer, cType, startReading, presentReading, nCMUsed, amountDue); System.exit(0); } // end of main method //Computes and returns the average of the elements an array of floating point numbers public static double computeAverage(double[] values){ double total=0; // to hold the total of all elements double average=0; // to hold the average for (double element : values) // add the elements total = total + element; //compute the average average = total/values.length ; // total divided by number of elements return average; } //Computes and returns the average of the elements an array of integers public static double computeAverage(int[] values){ double total=0; // to hold the total of all elements double average=0; // to hold the average for (int element : values) // add the elements total = total + element; //compute the average average = (double) total/values.length ; //total divided by number of elements return average; } /* * The following method finds and returns the index of the element with the lowest value * from an array of positive integers. * The Linear Search algorithm is applied. */ public static int findLowest(int[] values){ int result=values[0]; // let lowest be the first element int lowestIndex = 0; // set the lowest index to the first index for (int i=1; i<values.length; i++ ) // find out if an element after the first is lower { if (values[i] < result) { result = values[i]; // then set lowest index to the index of lower element lowestIndex = i; } } return lowestIndex - 1; // subtract 1 to get the month (index 0 = January) } /** *Finds and returns the index of the element with the highest value from an array of integers*/ public static int findHighest(int[] values){ int result=values[0]; // let highest be the first element int highestIndex = 0; // set the highest index to the first index for (int i=1; i<values.length; i++ ) // find out if an element after the first is higher { if (values[i] > result) { result = values[i]; //then set highest index to the index of higher element highestIndex = i; } } return highestIndex - 1; // subtract 1 to get the month (index 0 = January) } /** *This method prints the bill summary which contains the name of the consumer, type, meter reading of the beginning year, average mothly reading and payment, and the months with highest and lowest water consumption*/ public static void showSummary(String n, char t, int[] previous, int[] present, int[] c, double[] amount){ System.out.println(); System.out.println("Annual Water Bill Summary"); System.out.println("Name of Consumer: " + n); System.out.print("Type of consumer: "); if (Character.toLowerCase(t) == 'r') System.out.println("Residential"); if (Character.toLowerCase(t) == 'c') System.out.println("Commercial"); System.out.println("Meter reading at the beginning of year = " + previous[0] + " cubic meters"); System.out.printf("%15s%15s%15s%20s%n", "---------------", "--------------", "----------------", "--------------------"); System.out.printf("%15s%15s%15s%20s%n", "Month", "End Reading", "Consumption", "Amount Paid"); System.out.printf("%15s%15s%15s%20s%n", "---------------", "--------------", "----------------", "--------------------"); for (int index=0; index < previous.length; index++){ System.out.printf("%15s%15d%15d%20.2f%n", monthInWord(index+1), present[index],c[index] , amount[index]); } System.out.printf("%15s%15s%15s%20s%n", "---------------", "--------------", "---------------", "--------------------"); System.out.println("Average Monthly Reading = "+ computeAverage(c)); System.out.println("Average Monthly Payment = "+ computeAverage(amount)); System.out.println("Month with Lowest Water Consumption = "+ monthInWord((findLowest(c) + 1 ))); System.out.println("Month with Highest Water Consumption = "+ monthInWord((findHighest(c) + 1))); System.out.printf("%15s%15s%15s%20s%n", "---------------", "--------------", "---------------", "--------------------"); return; } // This converts numberical value into months public static String monthInWord(int m){ String r=""; switch ( m ){ case 1 : r = "January"; break; case 2 : r = "February"; break; case 3 : r = "March"; break; case 4 : r = "April"; break; case 5 : r = "May"; break; case 6 : r = "June"; break; case 7 : r = "July"; break; case 8 : r = "August"; break; case 9 : r = "September"; break; case 10 : r = "October"; break; case 11 : r = "November"; break; case 12 : r = "December"; } // end of switch return r; } // end of monthInWord method //This introduces what the program does. public static void showIntroduction(){ System.out.println("The water bills for the 12 months of a year by a water service\n" + "subscriber is summarized as follows."); return; } //This will accept the value of meter reading at the beginning of the year. public static int readStartReading(){ //Declare local variables boolean pFlag; int reading = 0; do { pFlag = false; try { System.out.print("Enter the meter reading at the beginning of the year: "); //Provide the input statement Scanner kbd = new Scanner(System.in); reading = Integer.parseInt(kbd.nextLine()); } catch (NumberFormatException x){ pFlag = true; System.out.println("You have to enter a number."); } if (reading < 0){ System.out.println("The beginning meter reading cannot be negative."); } } while (reading < 0 || pFlag); return reading; } //This will accept readings each month of the year. public static int readEndOfMonthReading(int start, int month) { //Declare local variables boolean problemFlag; int reading = 0; do { try { problemFlag = false; System.out.print("Enter the meter reading for month " + monthInWord(month) + ": "); //Provide the necessary input statement Scanner kbd = new Scanner(System.in); reading = Integer.parseInt(kbd.nextLine()); } catch (NumberFormatException x){ problemFlag = true; System.out.println("You have to enter a number."); } if (reading < start) { System.out.println("Invalid datum entry! The present reading must be greater than the previous reading.") ; } } while (reading < start || problemFlag); return reading; } //This will read and accept the type of consumer. public static char readTypeOfConsumer(){ Scanner kbd = new Scanner(System.in); System.out.println(); System.out.println("------------------------------"); // Declare local variables char t; do { System.out.print("Enter the type of the consumer< you may type r for residential or c for commercial>: "); //Provide needed statement(s) t = kbd.next().charAt(0); if (t != 'r' && t !='R' && t != 'c' && t != 'C'){ System.out.println("The valid types are r for residential and c for commercial."); } } while (t != 'r' && t !='R' && t != 'c' && t != 'C'); return t; } //This will compute the amount due that is payed by the consumer. public static double computeAmountDue(int c, char t, int min1, double minB1, int min2, double minB2, float rate1, float rate2) { double amount = 0; switch (t){ case 'r': case 'R': if ( c <= min1 ) { amount = minB1; } else { amount = minB1 + (c-min1)*rate1; } break; case 'c': case 'C': if ( c <= min2 ) { amount = minB2; } else { amount = minB2 + (c-min2)*rate2; } } return amount; } } // end of class /* SHOW A SAMPLE RUN OF THE PROGRAM WITHIN THIS COMMENT DELIMITERS The water bills for the 12 months of a year by a water service subscriber is summarized as follows. ------------------------------ Welcome to the Water Bill Annual Summary program! This program will calculate and summarize your water bill for the year. Enter the name of the water consumer: Eunice ------------------------------ Enter the type of the consumer< you may type r for residential or c for commercial>: R Enter the meter reading at the beginning of the year: 290 Enter the meter reading for month January: 320 Enter the meter reading for month February: 330 Enter the meter reading for month March: 340 Enter the meter reading for month April: 350 Enter the meter reading for month May: 390 Enter the meter reading for month June: 420 Enter the meter reading for month July: 450 Enter the meter reading for month August: 520 Enter the meter reading for month September: 550 Enter the meter reading for month October: 620 Enter the meter reading for month November: 650 Enter the meter reading for month December: 720 Annual Water Bill Summary Name of Consumer: Eunice Type of consumer: Residential Meter reading at the beginning of year = 290 cubic meters --------------- -------------------------------------------------- Month End Reading Consumption Amount Paid --------------- -------------------------------------------------- January 320 30 720.00 February 330 10 180.00 March 340 10 180.00 April 350 10 180.00 May 390 40 1020.00 June 420 30 720.00 July 450 30 720.00 August 520 70 1920.00 September 550 30 720.00 October 620 70 1920.00 November 650 30 720.00 December 720 70 1920.00 --------------- ------------------------------------------------- Average Monthly Reading = 35.833333333333336 Average Monthly Payment = 910.0 Month with Lowest Water Consumption = January Month with Highest Water Consumption = July --------------- ------------------------------------------------- */
Write, Run & Share Java code online using OneCompiler's Java online compiler for free. It's one of the robust, feature-rich online compilers for Java language, running the Java LTS version 17. Getting started with the OneCompiler's Java editor is easy and fast. The editor shows sample boilerplate code when you choose language as Java and start coding.
OneCompiler's Java online editor supports stdin and users can give inputs to the programs using the STDIN textbox under the I/O tab. Using Scanner class in Java program, you can read the inputs. Following is a sample program that shows reading STDIN ( A string in this case ).
import java.util.Scanner;
class Input {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter your name: ");
String inp = input.next();
System.out.println("Hello, " + inp);
}
}
OneCompiler supports Gradle for dependency management. Users can add dependencies in the build.gradle
file and use them in their programs. When you add the dependencies for the first time, the first run might be a little slow as we download the dependencies, but the subsequent runs will be faster. Following sample Gradle configuration shows how to add dependencies
apply plugin:'application'
mainClassName = 'HelloWorld'
run { standardInput = System.in }
sourceSets { main { java { srcDir './' } } }
repositories {
jcenter()
}
dependencies {
// add dependencies here as below
implementation group: 'org.apache.commons', name: 'commons-lang3', version: '3.9'
}
Java is a very popular general-purpose programming language, it is class-based and object-oriented. Java was developed by James Gosling at Sun Microsystems ( later acquired by Oracle) the initial release of Java was in 1995. Java 17 is the latest long-term supported version (LTS). As of today, Java is the world's number one server programming language with a 12 million developer community, 5 million students studying worldwide and it's #1 choice for the cloud development.
short x = 999; // -32768 to 32767
int x = 99999; // -2147483648 to 2147483647
long x = 99999999999L; // -9223372036854775808 to 9223372036854775807
float x = 1.2;
double x = 99.99d;
byte x = 99; // -128 to 127
char x = 'A';
boolean x = true;
When ever you want to perform a set of operations based on a condition If-Else is used.
if(conditional-expression) {
// code
} else {
// code
}
Example:
int i = 10;
if(i % 2 == 0) {
System.out.println("i is even number");
} else {
System.out.println("i is odd number");
}
Switch is an alternative to If-Else-If ladder and to select one among many blocks of code.
switch(<conditional-expression>) {
case value1:
// code
break; // optional
case value2:
// code
break; // optional
...
default:
//code to be executed when all the above cases are not matched;
}
For loop is used to iterate a set of statements based on a condition. Usually for loop is preferred when number of iterations is known in advance.
for(Initialization; Condition; Increment/decrement){
//code
}
While is also used to iterate a set of statements based on a condition. Usually while is preferred when number of iterations are not known in advance.
while(<condition>){
// code
}
Do-while is also used to iterate a set of statements based on a condition. It is mostly used when you need to execute the statements atleast once.
do {
// code
} while (<condition>);
Class is the blueprint of an object, which is also referred as user-defined data type with variables and functions. Object is a basic unit in OOP, and is an instance of the class.
class
keyword is required to create a class.
class Mobile {
public: // access specifier which specifies that accessibility of class members
string name; // string variable (attribute)
int price; // int variable (attribute)
};
Mobile m1 = new Mobile();
public class Greeting {
static void hello() {
System.out.println("Hello.. Happy learning!");
}
public static void main(String[] args) {
hello();
}
}
Collection is a group of objects which can be represented as a single unit. Collections are introduced to bring a unified common interface to all the objects.
Collection Framework was introduced since JDK 1.2 which is used to represent and manage Collections and it contains:
This framework also defines map interfaces and several classes in addition to Collections.
Collection | Description |
---|---|
Set | Set is a collection of elements which can not contain duplicate values. Set is implemented in HashSets, LinkedHashSets, TreeSet etc |
List | List is a ordered collection of elements which can have duplicates. Lists are classified into ArrayList, LinkedList, Vectors |
Queue | FIFO approach, while instantiating Queue interface you can either choose LinkedList or PriorityQueue. |
Deque | Deque(Double Ended Queue) is used to add or remove elements from both the ends of the Queue(both head and tail) |
Map | Map contains key-values pairs which don't have any duplicates. Map is implemented in HashMap, TreeMap etc. |