Sunday, May 25, 2025

Reading input with Scanner

 We have seen how to do math, and we’ve worked with both Math and Random by now, so we’ve used at least one import statement (to gain access to Random from java.util).


Let’s now look at another member of java.util, the Scanner class. Scanner is one of the ways you can make a Java class interactive with the user.

You might, for instance, want to modify HelloWorld to not say “Hello World” anymore, but “Hello Bob” if the user’s name is Bob, “Hello Sue” if the user’s name is Sue, and so on.

To find out the user’s name, you need to have a way for them to type it into the program, and for the program to accept it and do something with it. That’s the primary usecase for Scanner—to read in data passed in by typing it into the console with the keyboard. The console is the area at the bottom of your screen that appears when you run something, where, for example, “Hello World” appeared when you ran your first program.

Let’s look at this real program I wrote in 2017 while in AP Computer Science Principles in high school, the very first time I used Scanner.

import java.util.Scanner; 

/* Import the Scanner library, not a default, to be able to create

a new Scanner Object. */

 

public class TabSplitter

 

{

               public static void main (String[] args)

               {

                              System.out.println("Welcome to Tab Splitter!");    

 

                              Scanner BillAmt = new Scanner(System.in);           

                              System.out.println ("Please enter a bill amount.");

                              /* Use Scanner to capture this input.*/

                              double bill = BillAmt.nextDouble();

                              //Save it as a double//

                             

                              Scanner TipPercent = new Scanner(System.in);   

                              System.out.println ("Please enter an tip rate.");

                              double tip = TipPercent.nextDouble();

                              //Use another Scanner object to capture this input.//

                              // Save it as a double.//

                             

                              Scanner Customers = new Scanner(System.in);  

                              System.out.println ("How many customers are splitting the bill?");

                              int customers = Customers.nextInt();

                              double billamount = bill * (1+tip);    

                              /*Use another Scanner object to capture this input.*/

                              // Save it as a double.//

                              System.out.println ("Your total, without tip is $" + bill);

                              System.out.println ("Your total, with tip is $" + billamount);

                              System.out.println ("With " + customers + " customers splitting the bill, each should pay " + (billamount/customers));              

                              /* Using a combination of string literals and varibles (doubles, specifically), print out the desired information.*/

               }             

}


We can see, first of all, the all-important import statement for Scanner is import java.util.Scanner;

You create Scanner objects with their name, the “new” keyword, and the Scanner class. But here, you also pass in a parameter—where Scanner is getting the information it is reading in. System.in, by default, is the keyboard.

so a call to

Scanner scan = new Scanner(System.in);

Creates a Scanner object called scan and lets scan read what is typed in via the keyboard.

One minor style note (forgive me—I didn’t know any better then; but this is a sign that you can and will improve with time and practice!): In Java, nothing prevents you from naming things as I did, as in “TipPercent” with a  capital T, or “billamount” with a lowercase A, but, if I were writing those variable names today, knowing what I know now in 2025, I would have called them tipPercent (lowercase t, uppercase P) and billAmount (lowercase b, uppercase A). This is more correct camelCase, and is just a standard convention in Java that a lot of develpoers like—but not following this convention (as I did not, in 2017) will not cause an error.

Scanner has a number of useful methods for reading in data of various types—ints, strings, doubles, chars, etc.—just like Random had random() and random(int) for different purposes.

If you want to read in an int, then look at this line here, and use the nextInt() method: int customers = Customers.nextInt();

If you want to read in a double, then look at this line here for guidance, and use nextDouble()-- double tip = TipPercent.nextDouble();

If you want to read in text, for example, for a modified HelloWorld which we’ll call HelloYou, then use next() or nextLine().

import java.util.Scanner;

 

public class HelloWorld {

    public static void main(String[] args) {

        Scanner scanner = new Scanner(System.in);

        System.out.print("Enter your name: ");

        String name = scanner.next();

        System.out.println("Hello, " + name + "!");

    }

}

This would also work:

import java.util.Scanner;

 

public class HelloWorld {

    public static void main(String[] args) {

        Scanner scanner = new Scanner(System.in);

        System.out.print("Enter your name: ");

        String name = scanner.nextLine();

        System.out.println("Hello, " + name + "!");

        scanner.close();

    }

}

This also serves as a good time to introduce an important concept about Strings. To combine the strings “Hello” and “Bob” into “Hello Bob”, Java uses the + operator, and we call this concatenation. You will learn much more about Strings later on.

The second example, with nextLine() reading in the name, also has an important feature I left out from the first example on purpose—after you’re done using it, the second example “closes” its Scanner instance with the close() method. This is important because it doesn’t let Scanner read any more than you want, preventing security issues, and problems called memory leaks (which used to cause programmers a lot of frustration in older languages like C). If you want to “be a good Boy Scout,” as my AP Computer Science teacher, Whit Hubbard, told us, then close your Scanners when you’re done! 

No comments:

Post a Comment

Switch

 Other than if/if-else/if-else if-else and the ternary operator, there is yet another common and important conditional expression in Java th...