Java Reference
In-Depth Information
The final step of the algorithm is to display the value of y . This can be achieved by the
following two lines.
System. out . print ( "The temperature in Fahrenheit is: " );
System. out . println (y) ;
The first line prints the string that is specified in the double quotes. Note that all string
literals in Java need to be surrounded by double quotes. The second line prints the value of
y .Notethatthe print method can take any input: for example, integer, double, character,
and even an object. The second line of the code uses the println method instead of the
print method because we want to print a new line at the end.
With small modifications, our degree Fahrenheit to degree Celsius program will look as
1 package helloworld ;
import java . util .
4 public class Main
public static void main(String args []) {
int x;
double y,c;
System . out . p r i n t ( "Enter temperature is Celsius: " );
Scanner keyboard = new Scanner(System. in) ;
x=keyboard . nextInt () ;
c = 9/5;
y = 32+c x;
System . out . p r i n t ( "The temperature in Fahrenheit is: " );
System . out . p r i n t l n ( y ) ;
Let us first examine the program line by line. Line 1 defines the package. From now on,
for simplicity, we will create the programs in the default package and omit the package line.
Note that defining the package is a statement and, as such, is followed by a semicolon. If
we delete the semicolon, NetBeans will underline the whole line in red. If we hover over the
red line with the mouse, it will tell us that we have forgotten the semicolon. Line 2 tells
Java that we want to use the java.util library. This is where most of the utility classes
are stored. For example, we need this library in order to read input from the keyboard.
Since this is such an important library, we will include it in almost every program. Note
that some of our example programs will skip the import section. In order to see how to
reproduce the include lines, delete the second line of the code. The Scanner class will now
be underlined in red indicating an error. Right-click on the code that is underlined in red
and select Fix Imports . You will be given a chance to add the import that you need. In
our case, we can select java.util.Scanner .Notethat import java.util.* imports all
classes from the library java.util . Conversely, the statement import java.util.Scanner
imports only the Scanner class library.
Search WWH ::

Custom Search