Wednesday, 17 May 2017

Tutorial 13: Getting User Input



So, in all the past tutorials, we have been setting the values of the member variables of our classes from within the program. However, let’s say that you want the use to input their details and use these in the program. If you have been following my tutorials, you might have noticed that I use a Person class a lot in my examples. The Person class that we created looks something like this:

public class Person {
            private String name;
            private int age;
            private int id;
            public static void main(String[] args) {
                        Person person1 = new Person();
                        person1.name = “Brian”;
                        person1.age = 25;
                        person1.id = 11111111;
            }
}

In the above program, we are setting the name, age and id variables from within the code of the program. However, let’s say that we want someone to input their name, age and id…. How do we accomplish this?

Java has a class known as the Scanner class, which we can use to get input from the user. In itself, Java has many many classes with even more functions. These help us do amazing stuff. Moreover, there are people out there who have created collections of classes known as libraries that give you a lot of functionality. Scanner is one such inbuilt class that is found in the standard Java library.

In order to use the Scanner class, we need to create an object of the type Scanner like this:

Scanner scannerObject = new Scanner(System.in);

What the above statement does is that it creates a new Scanner object and in the constructor, it tells Java that you will use the computer input system to collect data from the user.

Now the next thing is to create an object of the type you want the user to input. What I mean is that when the user inputs the data, there needs to be a variable that will store the data. And naturally, this variable needs to of the same type as the data that is being input. For example, if you want the user to input their name, which is of type String, you have to create a variable of type String to hold this data.

Another thing is that the Scanner object you create can be used to input any type of data. You can use the same scanner object to input String, double, float, int, etc. So let’s say I want to input the name, age and id of a new Person object. First, I have to create the Person object, and then create the Scanner object and then use this Scanner object to set the values of the different variables. Here is an illustration:

            public static void main (String[] args) {
Person person1 = new Person ();
                        Scanner personInfo = new Scanner (System.in);
                        person1.name = personInfo.nextLine();
                        person1.age = personInfo.nextInt;
                        person1.id = personInfo.nextInt;
                        personInfo.close();
            }

So from the above example, you can see that the Scanner class has a function called nextLine() that collects values of type String. The Scanner class has a function called nextInt() that collects values of type integer. The Scanner class has a function called nextDouble() that collects double values. The Scanner class has a function called nextFloat() that collects values of type float.

After inputting all the values we want using the Scanner class, you should close the Scanner object by calling the close() function. This is because failing to close the object results in the loss of memory, which Java calls leaking resources. Java will usually remind you to close objects of type Scanner to prevent leaking resources.

Now, I’ve been reminding you time and time again that it is good practice to declare the member variables of your class as private and use public methods known as getters and setters to access and set the values of these member variables. I will use this construct in the following example, where I will use setters and the Scanner class object to give the member variables a value.

public class Person {
            private String name;
            private int age;
            private int id;
public void setName (String name) {
            this.name = name;
}
public void setAge (int age) {
            this.age = age;
}
public void setId (int id) {
            this.id = id;
}
public String getName() {
            return name;
}
public int getAge() {
            return age;
}
public int getId() {
            return id;
}

            public static void main(String[] args) {
                        Person person1 = new Person ();
                        Scanner personInfo = new Scanner (System.in);
                        System.out.println(“Enter your name and press enter:”);
                        person1.setName(personInfo.nextLine());
                        System.out.println(“Enter your age and press enter:”);
                        person1.setAge(personInfo.nextInt());
                        System.out.println(“Enter your id and press enter:”);
                        person1.setId(personInfo.nextInt());

                        personInfo.close();
                       
                        System.out.println(person1.getName());
                        System.out.println(person1.getAge());
                        System.out.println(person1.getId());
            }
}

Figure 1: A program that shows how to get user input using the Scanner class.
So in this tutorial, I’ve shown you a way to get user input and use what they input to set the values for the member variables of the class objects. Please read this tutorial several times and practice creating your own classes, with your own variables, getters, setters and try to input the values as I’ve shown you above.

In case of any questions or comments, please drop them in the comment section below and I will make sure to address them. 

In the next tutorial, we are going to discuss a Java class known as StringBuilder and we will also learn how to format strings.

Until then, stay safe.

No comments:

Post a Comment