Page 230 - IT-802_class_12
P. 230
The variable total marks in our percentage calculator software can only have integer values. As a result, we define it to
be of type int, which is a Java keyword that denotes an integer data type. Because they can have fractional values, the
variables marks obtained and percentage are declared of type double (floating point numbers).
We declare these variables and assign them values using the = operator inside the main method, as given below.
int total_marks = 400;
double marks_obtained = 346;
double percentage = 0.0;
To calculate the percentage, we construct an expression using the total_marks and marks_obtained variables and
assign the value to the percentage variable. The * operator is used for multiplication and the / operator for division.
percentage = (marks_obtained/total_marks)*100;
To display the percentage in the IDE output window, we use the System.out.prinltn() method.
System.out.println(“Student1’s Percentage = “+percentage);
Notice that the variable to be displayed is not put within the double quotes. To print the word “Percentage”, we put it
inside double quotes, to display the value stored in the percentage variable, we put it outside the double quotes. The
+ operator within the System.out.println statement, concatenates the string given in double quotes and the value of
the variable.
To calculate the percentage for another student, we reuse the variables. We change the value of the variable
marks_obtained and calculate the percentage again. There is no need to change the total_marks because its value
remains the same as before.
marks_obtained = 144;
percentage = (marks_obtained/total_marks)*100;
System.out.println(“Student2’s percentage = “+percentage);
To write the percentage calculator program in NetBeans, follow the steps given below:
1 First, within the package HelloWorld (which was created in the previous section), we’ll create a new Class file. To
make a new file, go to File → New File (Ctrl + N).
2 In the New File dialog box that appears, under the Categories list, select Java and under the File Types list select
Java Class (they should be already selected).
3 Click on the Next button. The New Java Class dialog box appears.
228 Touchpad Information Technology-XII

