Input & Type Conversion


Disclaimer, there are a few ways to take input In Java, but I feel that this is the nicest way. But if your definition of “nice” does not align with my definition of “nice”, then you can explore and use another way!

Scanner Class

We need to use a Scanner Object to take input from the user.

Our programs don’t come with Scanners automatically, so we need to add the following line to the start of our programs in order to use the Scanner Class.

import java.util.Scanner;

Then, to create a Scanner Object, you will need to add this line:

Scanner scannyBoi = new Scanner(System.in);

Note that scannyBoi is just a name I picked for the variable to hold the Scanner. You can name it whatever you want. You’ll probably want to name it something short though, like “sc”.

We can use a different method to take input depending on what type of data we expect.

Input methods

Method

Description

nextLine()

Reads a String value, stopping at the \n from ENTER

nextInt()

Reads an int value

nextDouble()

Reads a double value


NOTE: If the user does not input the data type that the method expects, a runtime error will occur.

As always, there are others. But these are the most commonly used in our course.

To call these methods, you will need to use the Scanner Object that you had created earlier.

import java.util.Scanner;

public class Main {

   public static void main(String[] args) {

      Scanner scannyBoi = new Scanner(System.in);

      // Prompt an input with a print statement
     System.out.println("Enter name, age, and height:");

     
// String input
     String name = scannyBoi.nextLine();

     
// Numerical input
     int age = scannyBoi.nextInt();
     double height = scannyBoi.nextDouble();

     System.out.println("Name: " + name);
     System.out.println("Age: " + age);
     System.out.println("Height: " + height);

     scannyBoi.close();
  }

}


If the user enters a mix-matched data type, your program will break due to error.

For example, if you use nextInt() and the user types the String “Hello!”

There’s a way to handle this, but we won’t worry about it for now.

Clearing the Scanner

When you type something into the console, you press “enter”! Pressing “enter”, or creating a newline is a special char, \n.

When we use nextLine(), the Scanner will take everything including the \n, which was written in your String when you hit enter.

But when you do nextInt() for example, Java grabs the number, not the \n (since \n is not an integer value).


So to “clear” the \n for the next time you take input, you have to “clear the Scanner” of the hanging \n, by calling
nextLine() one time - just to collect that \n!

You should do this each time you take numerical input.

If you don’t, you’ll notice this most when you take a String value after taking a numerical value, as the user will never have the chance to type in any String after a number. (The program will take the \n as the String instead.)

import java.util.Scanner;

public class Main {

   public static void main(String[] args) {

      Scanner sc = new Scanner(System.in);

     

      // Example without "clearing" the Scanner

      System.out.print("Enter your favourite integer: ");

      int favInt = sc.nextInt();

      System.out.print("Enter your favourite colour: ");

      // Didn't clear the Scanner so this will pick up the \n

      String favColour = sc.nextLine();

      System.out.println("Your favourite number is " + favInt);

      // This won't work as expected

      System.out.println("Your favourite colour is " + favColour);

      // Example with clearing the Scanner

      System.out.print("Enter your favourite integer: ");

      int favInt2 = sc.nextInt();

      System.out.print("Enter your favourite colour: ");  

      sc.nextLine(); // CLEARING THE SCANNER - VERY GOOD YES

      // Now the user can type

      String favColour2 = sc.nextLine();

      // This will work fine   
     System.out.println("Your favourite number is " + favInt2);

      System.out.println("Your favourite colour is " + favColour2);

      sc.close();

   }

}


Closing the Scanner

When you’re done taking input, we can “throw out” our Scanner to save memory in our programs.

Even if we may not need that memory (since our programs in this course are pretty small) it’s still a good idea because not closing the Scanner can lead to “resource leaks”.

Most of the time this doesn’t affect your program, but resource leaks can sometimes cause your programs to behave strangely so it’s worth closing them just to cover your bases.

Casting

In Java, type casting is used to convert variable values from one primitive type to another.

There are two types of casting:

Widening casting can happen automatically, since it’s easy to put a small thing into a larger space.

Narrowing casting has to be done manually. When you put something large into a smaller space, not everything will fit. Therefore, you have to make the active choice to lose something.

public class Main {

   public static void main(String[] args) {

      // Widening

      int x = 8;

      double wideX = x; // Automatically casts to a double

      System.out.println(wideX);

   }

}

8.0

Narrowing Cast

To narrow cast, write the type you want in brackets in front of the value to be cast. For instance, (int) and (double).

public class Main {

   public static void main(String[] args) {

      // Narrowing

      double y = 1.8;

      int narrowY = (int)y; // Manually casting double to int

      System.out.println(narrowY);

   }

}

1

Parsing

If we wanted to convert an Object to a primitive type, we parse the data. In our course, we will see this most commonly when converting from String → int, or
String → double.

Integer.parseInt(str)

NOTE: Must be a value that could actually be converted to an int. For example, the call Integer.parseInt("Not a number") will break your code. Also, the call Integer.parseInt("1.8") would also cause an error, because parseInt() does not perform narrowing casts for you.

Double.parseDouble(str)

public class Main {

   public static void main(String[] args) {

      String numStr = "123";

      int intFromStr = Integer.parseInt(numStr);

      // Automatic widening cast

      double doubleFromStr = Double.parseDouble(numStr);

      // Showing results from parsing

      System.out.println(intFromStr);        

      System.out.println(doubleFromStr);

      // This will give an error

      // Since the String holds a decimal number, not an int

      /* String dubStr = "3.14";

      int badInt = Integer.parseInt(dubStr);

      */

   }

}

123

123.0