Today's programming exercise for beginner is to write a Java program to take input from user and find out maximum and minimum number and print them into console. Purpose of this article is to teach you how to get input from user in Java and how to use java.lang.Math class to perform some mathematical operation e.g. max, min or average. You can use Scanner class, added in Java 1.5 to read user input from console. Scanner needs an InputStream to read data and because you are reading from console, you can pass System.in, which is InputStream for Eclipse console, or command prompt, depending upon what you are using. This class also helps you to convert user input into require data type e.g. if user enter numbers then you must convert then into int data type and store them into int variable as shown in our example. You can use nextInt() method to read user input as Integer. Similarly you can use nextLine() to read user input as String. There are other methods available to read float, double, or boolean from command prompt. Once you got both the numbers, it just matter of using relational operator less than and greater than to find smaller and larger number, as shown in following example. After that you can Math.max() to find maximum of two numbers, it should be same as your earlier result. Similarly, we will ask User to enter number again and will display minimum of two. I also suggest you to read Head First Java 2nd Edition book, if you have just started learning Java. It is one of the best book to learn Java in quick time.
Read more »
No comments:
Post a Comment