Rent-a-car java program




















If user wants to proceeds, user is allowed to enter name and IC no. After that, the receipt will get displayed including all the details. Net RoseIndia. Program testing usually involves a set of representative test cases, which are designed to catch all classes of errors. Program testing is beyond the scope of this writing. Nested loops are needed to process 2-dimensional or N-dimensional data, such as printing 2D patterns. A nested-for-loop takes the following form:.

The following program prompt user for the size of the pattern, and print a square pattern using nested-loops. This program contains two nested for-loops. The outer loop repeats the inner loop to print all the rows. The coding pattern for printing 2D patterns is as follows.

I recommend using row and col as the loop variables which is self-explanatory, instead of i and j , x and y. Suppose that you want to print this pattern instead in program called PrintCheckerPattern :. You need to print an additional space for even-number rows. You could do so by adding the following statement before the inner loop. The break statement breaks out and exits the current innermost loop. The continue statement aborts the current iteration and continue to the next iteration of the current innermost loop.

Use them only if absolutely necessary. The body of the empty for-loop will execute continuously infinite loop. You need to use a break statement to break out the loop. Endless loop is typically a mistake especially for new programmers. You need to break out the loop via a break statement inside the loop body.. Example break : The following program lists the non-prime numbers between 2 and an upperbound. Let's rewrite the above program to list all the primes instead. A boolean flag called isPrime is used to indicate whether the current number is a prime.

It is then used to control the printing. Let's rewrite the above program without using break statement. A while loop is used which is controlled by the boolean flag instead of for loop with break. Example break and continue : Study the following program. In a nested loop, the break statement breaks out the innermost loop and continue into the outer loop.

At times, there is a need to break out all the loops or multiple loops. This is clumsy to achieve with boolean flag, but can be done easily via the so-called labeled break. You can add a label to a loop in the form of labelName : loop. In a nested loop, similar to labeled break , you can use labeled continue to continue into a specified loop. Again, labeled break and continue are not structured and hard to read. Example Labeled break : Suppose that you are searching for a particular number in a 2D array.

You can convert char '0' to '9' to int 0 to 9 by subtracting the char with the base '0' , e. That is, suppose c is a char between '0' and '9' , c - '0' is the corresponding int 0 to 9.

The following program illustrates how to convert a hexadecimal character , A-F or a-f to its decimal equivalent , by subtracting the appropriate base char. The most commonly-used String methods are as follows, suppose that str , str1 , str2 are String variables:. You could use the JDK built-in methods Integer. The runtime triggers a NumberFormatException if the input string does not contain a valid integer literal e. Similarly, you could use methods Byte.

You could use Double. You can use aStr. You can use method Boolean. Recall that you can use printf to create a formatted string and send it to the display console, e. There is a similar function called String. The following program prompts user a string, and prints the input string in the reverse order. The following program prompts user for a string, and checks if the input is a valid binary string, consisting of '0' and '1' only.

The following program prompts user for a binary string, and converts into its equivalent decimal number. The following program prompts user for a hexadecimal string and converts into its equivalent decimal number. Suppose that you want to find the average of the marks for a class of 30 students, you certainly do not want to create 30 variables: mark1 , mark2 , Instead, You could use a single variable, called an array , with 30 elements or items.

An array is an ordered collection of elements of the same type , identified by a pair of square brackets [ ]. To use an array, you need to:.

When an array is constructed via the new operator, all the elements are initialized to their default value, e. You can refer to an element of an array via an index or subscript enclosed within the square bracket [ ]. Java's array index begins with zero 0. For example, suppose that marks is an int array of 5 elements, then the 5 elements are: marks[0] , marks[1] , marks[2] , marks[3] , and marks[4].

To create an array, you need to known the length or size of the array in advance, and allocate accordingly. Once an array is created, its length is fixed and cannot be changed during runtime. At times, it is hard to ascertain the length of an array e. Nonetheless, you need to estimate the length and allocate an upper bound. Suppose you set the length to 30 for a class of students and there are 31 students, you need to allocate a new array of length 31 , copy the old array to the new array, and delete the old array.

In other words, the length of an array cannot be dynamically adjusted during runtime. This is probably the major drawback of using an array. There are other structures that can be dynamically adjusted. In Java, the length of array is kept in an associated variable called length and can be retrieved using " arrayName. In other words, for each reference to an array element, the index is checked against the array's length.

If the index is outside the range of [0, arrayName. It is important to note that checking array index-bound consumes computation power, which inevitably slows down the processing. However, the benefits gained in terms of good software engineering out-weight the slow down in speed.

Arrays works hand-in-hand with loops. You can process all the elements of an array via a loop, for example,. JDK 5 introduces a new loop syntax known as enhanced for-loop or for-each loop to facilitate processing of arrays and collections.

It takes the following syntax:. This loop shall be read as "for each element in the array The loop executes once for each element in the array, with the element's value copied into the declared variable. The for-each loop is handy to transverse all the elements of an array.

It requires fewer lines of code, eliminates the loop counter and the array index, and is easier to read. However, for array of primitive types e. This is because each element's value is copied into the loop's variable, instead of working on its original copy. In many situations, you merely want to transverse thru the array and read each of the elements.

For these cases, enhanced for-loop is preferred and recommended over other loop constructs. The following program prompts user for the length and all the elements of an array, and print the array in the form of [a0, a1, JDK 5 provides an built-in methods called Arrays. You need to import java. The following program prompts user for the number of students, and the grade of each student. It then print the histogram, in horizontal and vertical forms, as follows:.

The following program prompts user for a hexadecimal string and convert it to its binary equivalence. The following program prompts user for an integer, reads as int , and prints its hexadecimal equivalent.

In the above example, grid is an array of 12 elements. Each of the elements grid[0] to grid[11] is an 8-element int array. In other words, grid is a "element array" of "8-element int arrays".

Hence, grid. To be precise, Java does not support multi-dimensional array directly. That is, it does not support syntax like grid[3, 2] like some languages. Furthermore, it is possible that the arrays in an array-of-arrays have different length. Take note that the right way to view the "array of arrays" is as shown, instead of treating it as a 2D table, even if all the arrays have the same length.

At times, a certain portion of code has to be used many times. Instead of re-writing the code many times, it is better to put them into a "subroutine", and "call" this "subroutine" many time - for ease of maintenance and understanding. Two parties are involved in using a method: a caller , who calls or invokes the method, and the method called.

Example: Suppose that we need to evaluate the area of a circle many times, it is better to write a method called getArea , and re-use it when needed. In the above example, a reusable method called getArea is defined, which receives an argument in double from the caller, performs the calculation, and return a double result to the caller. In the main , we invoke getArea methods thrice, each time with a different parameter. Take note that there is a transfer of control from the caller to the method called, and from the method back to the caller, as illustrated.

Take note that you need to specify the type of the arguments and the return value in method definition. To call a method, simply use methodName arguments. For examples, to call the above methods:. Take note that you need to specify the type in the method definition, but not during invocation.

A method's name shall be a verb or verb phrase action , comprising one or more words. The first word is in lowercase, while the rest are initial-capitalized called camel-case. For example, getArea , setRadius , moveDown , isPrime , etc. Inside the method body, you could use a return statement to return a value of the returnValueType declared in the method's signature to return a value back to the caller. Suppose that you need a method to perform certain actions e. In the method's body, you could use a " return; " statement without a return value to return control to the caller.

In this case, the return statement is optional. If there is no return statement, the entire body will be executed, and control returns to the caller at the end of the body. Notice that main is a method with a return-value type of void. Recall that a method receives arguments from its caller, performs the actions defined in the method's body, and return a value or nothing to the caller.

In the above example, the variable double radius declared in the signature of getArea double radius is known as formal parameter. Its scope is within the method's body. When the method is invoked by a caller, the caller must supply so-called actual parameter s or arguments , whose value is then used for the actual computation.

The following program contains a boolean method called isMagic int number , which returns true if the given number contains the digit 8 , e. The signature of the method is:.

The following program contains various method for int array with signatures as follows:. In Java, when an argument of primitive type is pass into a method, a copy is created and passed into the method. The invoked method works on the cloned copy , and cannot modify the original copy.

This is known as pass-by-value. As mentioned, for primitive-type parameters, a cloned copy is made and passed into the method. Hence, the method cannot modify the values in the caller. It is known as pass-by-value. For arrays and objects - to be described in the later chapter , the array reference is passed into the method and the method can modify the contents of array's elements.

It is known as pass-by-reference. Before JDK 5, a method has to be declared with a fixed number of formal arguments. C-like printf , which take a variable number of argument , cannot not be implemented. Although you can use an array for passing a variable number of arguments, it is not neat and requires some programming efforts. JDK 5 introduces variable arguments or varargs and a new syntax " Type Varargs can be used only for the last argument. The three dots The compiler automatically packs the varargs into an array.

You could then retrieve and process each of these arguments inside the method's body as an array. It is possible to pass varargs as an array, because Java maintains the length of the array in an associated variable length.

A method that takes a double parameter can accept any numeric primitive type, such as int or float. This is because implicit type-casting is carried out. However, a method that take a int parameter cannot accept a double value. This is because the implicit type-casting is always a widening conversion which prevents loss of precision. An explicit type-cast is required for narrowing conversion. Read " Type-Casting " on the conversion rules.

In Java, a method of a particular method name can have more than one versions, each version operates on different set of parameters - known as method overloading. The versions shall be differentiated by the numbers, types, or orders of the parameters. Suppose you need a method to compute the sum of the elements for int[] , short[] , float[] and double[] , you need to write all overloaded versions - there is no shortcut. Suppose that we wish to write a method called isOdd to check if a given number is odd.

You may rewrite the condition:. The above produces the correct answer, but is poor. For boolean method, you can simply return the resultant boolean value of the comparison, instead of using a conditional statement, as follow:.

JDK provides many common-used Mathematical methods in a class called Math. The signatures of some of these methods are:. Java's main String[] args method takes an argument: String[] args , i. This is known as "command-line arguments", which corresponds to the augments provided by the user when the java program is invoked.

For example, a Java program called Arithmetic could be invoked with additional command-line arguments as follows in a "cmd" shell :. Each argument, i.

Java runtime packs all the arguments into a String array and passes into the main method as args. For this example, args has the following properties:.

Bitwise operators perform operations on one or two operands on a bit-by-bit basis, as follows, in descending order of precedences. Bit-shift operators perform left or right shift on an operand by a specified number of bits. Left-shift is always padded with zeros for both signed and unsigned. There is no difference between the signed-extended and unsigned-extended left shift, as both operations pad the least significant bits with zeros.

As seen from the example, it is more efficient to use sign-right-shift to perform division by 2, 4, The bitwise operators are applicable to integral primitive types: byte , short , int , long and char. There are not applicable to float and double. Bit-shift operators are not applicable to boolean s. Before writing a program to solve a problem, you have to first develop the steps involved, called algorithm , and then translate the algorithm into programming statements.

This is the hardest part in programming, which is also hard to teach because the it involves intuition, knowledge and experience. An algorithm is a step-by-step instruction to accomplice a task, which may involve decision and iteration. It is often expressed in English-like pseudocode , before translating into programming statement of a particular programming language.

There is no standard on how to write pseudocode - simply write something that you, as well as other people, can understand the steps involved, and able to translate into a working program. Ancient Greek mathematicians like Euclid and Eratosthenes around BC had developed many algorithms or step-by-step instructions to work on prime numbers. By definition, a prime is a positive integer that is divisible by one and itself only. To test whether a number x is a prime number, we could apply the definition by dividing x by 2, 3, 4, If no divisor is found, then x is a prime number.

A positive integer is called a perfect number if the sum of all its proper divisor is equal to its value. Other perfect numbers are 28 , , By definition, GCD a,b is the largest factor that divides both a and b. Before explaining the algorithm, suppose we want to exchange or swap the values of two variables x and y. Explain why the following code does not work.

Otherwise, we replace a by b ; b by a mod b , and compute GCD b, a mod b. Repeat the process until the second term is 0. Try this out on pencil-and-paper to convince yourself that it works. Type mismatch, "Num" implies numbers which are not strings, could be really helpful to explain this in documentation. Also, don't shorten function names like this. You're one step away from getRN. Reduce typing via autocomplete, not text compression. No unit defined, so tracking down business logic bugs is hard.

Put it in comments, or, even better, in the function name. Something like getFuelCapacityInLiters. Actually, if you combine the two, they should probably be "current" and "max" fuel. Keep your terms related. And I'd sort them around so that the "current fuel" definition comes before the "max fuel" function definition. That way it reads easier. What's the difference between this method and isTankFull?

The people in the vehicle? Mind you, the entire reason I can get this confused about the requirements is because you put no explanation in code what so ever.

This sort of thing is hell to maintenance programmers. This shouldn't be a Boolean , it should be a boolean. Else I'll toss null in. And bad things will happen. I know you're likely to add fuel to a vehicle in real life, but tracking applications usually don't do all the things that you'd do in real life. They just track the current status - which is likely to deviate from estimations, so setFuel would probably be better. That is to say, I'm missing a setter. Numbers come out!

It makes no sense! Also, are those meters, kilometers, miles, yards, feet, inches This is a possible design flaw, but understandable, I think. I'd love to talk about it some more, but the other issues are far more important. I wonder why being small matters, though. In an interface you NEED to define the semantics. If you define the semantics in function names and argument names then it is much easier to verify implementations.

This is missing braces which you should add because they are a sanity check - missing braces means unfinished thoughts means unfinished logic - at least for me, and I freak out whenever the braces are missing. Except that, looking at the conditional, there is no need to compare to 0, you can just compare to other values.

This is still silly, of course, there is no need to keep track of internal state of isFull , it is trivially derivable:. Except the naming is flawed; this should really be called isTankFull. Adjust your interface as needed here.

They go at the top of the function where possible. Before any variable declarations. No need to reserve memory for something that you're not going to use. Also, it allows you to first perform checks, then have ALL the code below assume sane values. You cannot have tariff 2 only in the else. Calculate them using some if statements. Then, when you have the values use them in the System. This is good because you can add simply add whatever you want to the ints and you will always have their values.

The reason this question is being downvoted is because you've got all the tools to answer the question and you've just not got a grasp of the logic required, its not generally good practice to do this since it seems lazy, even if you've tried really hard.

How are we doing? Please help us improve Stack Overflow. Take our short survey. Stack Overflow for Teams — Collaborate and share knowledge with a private group. Create a free Team What is Teams? Collectives on Stack Overflow. Learn more. Asked 3 years, 6 months ago.

Active 3 years, 6 months ago. Viewed 1k times.



0コメント

  • 1000 / 1000