Java Program to Display Odd Numbers From 1 to 100In Java, the most popular way to read numbers from standard input is to use the Scanner class. Sometimes, we also use the class BufferedReader class to read a number. It provides different methods related to the input of different primitive types. In this section, we will learn how to create Java programs to read numbers from the user through the standard input, such as the keyboard. We can use the following classes to read a number:
Using Scanner classThe Scanner class is defined in the java.util package. So, it is mandatory to import the package while using the Scanner class. The class also provides the methods to take input of different primitive types, such as int, double, long, char, etc. In order to read a number (integer) from the user, we first create an object of the Scanner class and then invoke the nextInt() method. It is the most preferred method to take input of primitive types. Similarly, we can also use nextDouble(), nextLong(), nextFloat(), etc. method if we want to read double, long, and float type from standard \input. ReadNumberExample1.java Output: Enter a number: 89 The number entered by the user is: 89 Using BufferedReader ClassJava BufferedReader class is used to read the text from a character-based input stream. It provides the method readLine() to read data line by line. It makes the performance fast. It inherits the Reader class. It is defined in the java.io package so, we must import the package at the starting of the program. The disadvantage to use this class is that it is difficult to remember. To read a number, first, create a constructor of the BufferedReader class and parse a Reader as a parameter. We have parsed an object of the InputStreamReader class. After that, we have invoked the parseInt() method of the Integer class and parses the readLine() method of the BufferedReader class. The readLine() method reads a line of text. ReadNumberExample2.java Output: Enter a number: 23 You have entered: 23 In the above example, we can merge the following in a single line. Or Using Command-Line ArgumentsIn the command line arguments, we read the number from the standard input at the execution time of the program. The arguments passed from the console can be received in the java program and it can be used as an input. When JVM receives the command line arguments, it wraps these numbers and transferred to args[]. In the following program, we have provided the number at the execution time and converted that numbers into the integer by using the Integer.parseInt() method. Because command line arguments accept only String type. To run the program, follow the steps, given below:
Where 12 and 90 are command-line arguments. Note: You can provide your input.ReadNumberExample3.java Output: The sum of 12 and 90 is 102
Next TopicJava Programs
|