User Input


Hello everyone to today’s post, I will be writing about my favorite classes in Java, which is the Scanner class. Before we start looking into Scanner class,  let’s quickly review why we need class and what is the importance of it in Java programming.

Method, function and class

Java has a set of code which is known as a “method” and it can be only run when it is called.

The method is used to do required jobs, functions, by using parameters. The method needs to be declared by using a “class” and the name of the method is followed with “()”.  The following is an example of java programming method to demonstrate required coding syntax;

public class name of class {

  static void name of method() {

    // written code 

  }

}

Scanner class

The purpose of scanner class is to get the user input, so you can interact with the code that you made. Java automatically downloads the java.util package to utilise this class.

Before we begin I have a list of methods for input types to read each different type of values (String, Boolean, etc.).

Now before I continue,  an example would be the following;

//Remember to give a variable name for the string.  I named it as “test” in the following example.

String test;

Scanner scan = new Scanner(System.in);

//and to read it, we would need the following code.

test = scan.nextLine();

Now,  we have a basic understanding of how to utilise scanner class,  let’s see a few examples below.  Don`t worry! It could be a little confusing but we will use scanner class in the coming post with multiple examples.

Example 1- User input is your name and program calls your name says Hello! 

Example 2 – User input is minutes and program converts to hours 

I hope you start warming up to Java.  Next post,  we will look into string & math methods.

Leave a comment