Taking Input from the User


In the addition program that we have written, we have initialised the variables firstNumber and secondNumber with 3 and 4. Wouldn’t it be better if you could ask your friend to enter his own values and then display the sum of those two numbers? There are several ways to do it in Java. But here, we shall look at one simple way by using the Scanner class. You may not be able to understand every line of code that we would be writing here but still at the end, you will know how you can take different types of input- integers, real numbers, Strings from the user just like the way you are now capable of writing simple programs like displaying ‘Hello World!’ and adding two numbers even when you could not fully understand what public, static, void and other words meant. Things would become clearer as we proceed to other topics. For now, we shall look at the Scanner class.
As already said, Java has a number of predefined classes which we can use. These classes are just like the HelloWorld and Addition classes that we have written but they do not contain a main method. Instead, they have some variables, constructors and some different methods. With the help of constructors, we instantiate (create) objects from these classes. We can create as many objects as we want from a single class and each of them have their own set of instance variables. And, we call the methods of these objects to perform tasks.
These predefined classes are organised in the form of packages. For now, you can think of a package as a simple collection of classes. Before we can use the class, we need to either import the entire package or the class. We import the Scanner class using the following line.
import java.util.Scanner;
The import statement should be the first line in our program. And then as usual we write the code for our class or program, similar to what we have done earlier.
import java.util.Scanner;
   public class Addition {
      public static void main(String[] args) {
      // some code here
   }
}
This is the structure of a class which we are already familiar with. Now, we need to write some code in the main method to perform the intended task. Before we write the code, let us look at how information can be passed from the keyboard to our program using the Scanner class.
Information flows as a stream just like the way water flows through a hose. The System class which we have used contains two pre-defined streams. One is the output stream (out) which is connected the console. We have used it in our earlier programs to print information on the screen. The other stream is the input stream (in) which is by default connected to the keyboard. We need to obtain the stream and convert the information in that stream into meaningful data like integers and Strings. The input stream object (in) is accessed by the statement System.in ‘System’, as we have already said is a predefined class and ‘in’ is a variable in that class which holds a reference to an input stream object. We now use this in object to create a Scanner object. As we have already said, to create an object from a class, we use the constructor of that class. The constructor just like methods may require arguments. Remember that when we have used the print() or println() methods, we have passed String arguments like ‘HelloWorld’. A Scanner constructor requires an input stream object as an argument. Therefore we pass the in object to the Scanner constructor and create a Scanner object named s in the following way.
Scanner s = new Scanner ( System.in );
Note that s is an identifier- a variable name just like firstNumber and secondNumber. And therforore you can give any name that you want. The proper way to access a variable of another class (here, in) is to refer to its name by specifying the class name followed by a dot operator and the variable name.
The keyword new is used to create an object. We will learn more about creating objects later on. If you have understood all that has been stated till now, it’s a good thing. If you haven’t, do not bother. Simply remember that the obove statement is used to create a Scanner object named s.
The Scanner class has several methods which are used to take different types of inputs. They are listed in the table below.
Method Description
nextByte() Accept a byte
nextShort() Accept a short
nextInt() Accept an int
nextLong() Accept a long
next() Accept a single word
nextLine() Accept a line of String
nextBoolean() Accept a boolean
nextFloat() Accept a float
nextDouble() Accept a double
Suppose, we want to accept an integer and store it in the variable firstNumber, we write the following statement:
int firstNumber = s.nextInt();
In a similar way, we can accept other data types from the user. The following code shows the complete program which accepts two numbers from the user and adds them and displays the result.
import java.util.Scanner;
public class Addition {
   public static void main(String[] args) {
      Scanner s = new Scanner(System.in);
      System.out.print(“Enter first number: “);
      int firstNumber = s.nextInt();
      System.out.print(“Enter second number: “);
      int secondNumber = s.nextInt();
      int sum = firstNumber + secondNumber;
      System.out.println(“The result of addition was ” + sum);
   }
}
Following shows a sample output when we enter the numbers 34 and 43 as input.
Enter first number: 34
Enter second number: 43
The result of addition was 77
In a similar way, you can take other data types as input.
Following program shows another example usage of the Scanner class. Here we take the marks of a student in three subjects and display his average and his average as in done a progress report.
import java.util.Scanner;

Public class Average Marks {

Public static void main(String[] args) {
      Scanner s = new Scanner ( System.in);
      System.out.print(“Enter your name: “);
      String name=s.next();
      System.out.print(“Enter marks in three subjects: “);
      int marks1=s.nextInt();
      int marks2=s.nextInt();
      int marks3=s.nextInt();
      double average = ( marks1+marks2+marks3)/3.0;
      System.out.println(“\nName: “+name);
      System.out.println(“Average: “+average);
   }
}

There are a few things worth mentioning regarding this code. The first thing is that we have taken the marks of the student in three subjects by using the nextInt() method repeatedly. We haven’t prompted thrice for input. While, there appears nothing extraordinary in this way of programming, let’s look at the output in different executions.
Following are some sample outputs.
Enter your name: Sai
Enter marks in three subjects: 100 98 99

Name: Sai
Average: 99.0

Enter your name: Sai
Enter marks in three subjects: 100
99
98

Name: Sai
Average: 99.0

Enter your name: Sai
Enter marks in three subjects:

100

99
98

Name: Sai
Average: 99.0

Enter your name: Sai
Enter marks in three subjects:

100 99

98

Name: Sai
Average: 99.0

We have given the same input in all the cases but the way in which we have input the values was different. In the first case, we separated the different marks with a space. In the second case, we have pressed the enter key after entering each subject’s marks. In few of the outputs, we have also entered some blank lines but still the output was the same in all the cases. This is because of the way in which the input from the keyboard. Whatever in entered by us goes to the input steam, in and then we extract data from it using the nextInt() method. What actually happens is that the data is separated into tokens. Token are pieces of information. Tokens are not generated randomly but by noting the delimiters. Every time, the delimiter appears, the input is split at that point and a new token is created. The default delimiter is a whitespace. A whitespace can be a tab, space, a new line or a combination of theses. For example- a new line followed by three spaces is also a delimiter. After the input is split into tokens, the tokens are accessed by the method nextInt(). In all the cases, the three tokens formed were the same and hence we got the same output.
Another thing has to be noted is the following statement:
double average = ( marks1 + marks2 + marks3 ) / 3.0;
The first thing is the use of parentheses. If we have omitted the parentheses, then marks3 would have been divided by three first and then added to marks1 and marks2. Precedence of operators exists in Java just as in mathematics. In Java /, * and % have equal preference which is higher than the preference for + and -. In order to alter the order in which evaluation is performed, we use parentheses. Change 3.0 to 3 and you will notice that the average printed would be incorrect. This is because, the three integers marks1, marks2 and marks3 on addition give an integer and an integer on division with another integer gives another integer and not a floating point number. In simpler words, an integer on division with another integer gives the quotient and not the entire result that includes the remainder part in the form of a decimal part. However, when the expression involves atleast a single decimal, we get the decimal part of the calculation as well. That is why we have written 3.0 instead of 3. We shall see more about mathematical calculations in the next chapter.
Author: , 0000-00-00