Java TOPIC 08 – KEYBOARD INPUT & STRING
BASICS LESSON NOTE INTERACTIVITY Most programs
require some form of interactivity from the user. One way to achieve this is to get data from
the keyboard. Getting input
from keyboard could involve dealing with errors that could occur. This complexity is something that we are
not ready to deal with. Therefore, we
will use an existing class that provides this functionality for us. INTRODUCING THE SCANNER
CLASS The Scanner
class allows us to create a Scanner object that can deal with user input for
us. We create a Scanner object called scr by using: Scanner scr =
new Scanner(System.in); Once the
Scanner object is created, we can ask it to get user input as many times as
we want. Note that
when you create the object, you will have to import java.util.Scanner; Of course,
Eclipse will do that for you if you want. USING THE SCANNER OBJECT
TO GET INPUT We can use one of several methods inside the Scanner class to
get us the input from the user. A method
is simply a series of statements grouped together under a single name. The methods that we will use are called next(), nextInt() and nextDouble(). Any one of the following three lines will do. You simply pick the one that gives you to
correct type of data. String s1 = scr.next(); int
i = scr.nextInt(); double d = scr.nextDouble(); FULL
PROGRAM EXAMPLE Here
is a program that will ask a user to enter the price of an item and it will
calculate its full price after an additional 13% tax. import java.util.Scanner; public class Tax { public static void main(String[] args) { System.out.println("Enter the price of an item"); Scanner scr =
new Scanner(System.in); double price = scr.nextDouble(); double totalPrice =
price * 1.13; System.out.print("The total price after 13% tax is
"); System.out.print(totalPrice); } } STRINGS A
String is a sequence of characters.
Strings are always denoted inside double quotes. Strings
are different than variables because they are objects. There is a String class that contains
different methods that we can use to manipulate Strings. However, for now, we will only with the
basics. CREATING A
STRING We
create a String in a similar way as we created a Scanner object. String
s = new String("hi there"); However,
because Strings are so common, there is a short form to create them. String name =
"Patrick"; STRING
CONCATENATION We
can combine multiple Strings by using the + operator. This will simply glue the Strings together. EXAMPLE The
following statement String name = "Pat" +
" " + "Omer" + " " + "Campeau"; will
give the value "Pat Omer Campeau" to
the String variable name. PROGRAM EXAMPLE Here
is an example of a program that will ask the user for their name and output a
greeting message. import java.util.Scanner; public class Greeting { public static void main(String[] args) { System.out.println("Enter your name"); Scanner scr = new Scanner(System.in); String name = scr.next(); System.out.print("Hello " + name); } } |
|
|