Basics of Java Programming Input and The Scanner Class: CSC 1051 - Algorithms and Data Structures I
Basics of Java Programming Input and The Scanner Class: CSC 1051 - Algorithms and Data Structures I
Course website:
www.csc.villanova.edu/~map/1051/
Some slides in this presentation are adapted from the slides accompanying:
Review
Variables
A variable is a name for a location in memory, of a declared type
An assignment statement associates a value with a variable
A variable can be given an initial value in the declaration
int age;
double x = 3.2, y = -0.80;
"
age = 18;"
x = 3.3;"
String name = scan.nextLine();"
CSC 1051 M.A. Papalaskari, Villanova University
Variables
A variable is a name for a location in memory, of a declared type
An assignment statement associates a value with a variable
A variable can be given an initial value in the declaration
int age;
double x = 3.2, y = -0.80;
"
age = 18;"
x = 3.3;"
String name = scan.nextLine();"
CSC 1051 M.A. Papalaskari, Villanova University
Reading Input
The Scanner class is part of the java.util class
library, and must be imported into a program in
order to be used
The import statement goes at beginning of your
program (above class definition)
import java.util.Scanner;
import java.util.Scanner;"
"
public class TellMeAboutYou "
{ "
public static void main(String[] args) "
Enter your name: Fiona
{"
Enter your age: 17
int age;
"
Pleased to meet you, Fiona!
String name; "
Your age in dog years is 178.5
"
Scanner scan = new Scanner(System.in); "
"
System.out.print("Enter your name"); "
name = scan.nextLine(); "
"
System.out.print("Enter your age"); "
age = scan.nextInt(); "
"
System.out.println("Pleased to meet you, " + name + "!");"
System.out.println("Your age in dog years: " + age*10.5);"
}"
} name = scan.nextLine();" Inspired by: http://www.onlineconversion.com/dogyears.htm
CSC 1051 M.A. Papalaskari, Villanova University
Input methods
nextInt() input an int
nextDouble() input a double
nextLine() input a String (until end of line)
next() input a String token (one word or
other delimited chunk of text)
White space (space, tab, new line) are used to
separate input tokens
import java.util.Scanner;"
"
public class TellMeAboutYou "
{ "
public static void main(String[] args) "
{"
Enter your name and age: Fiona 17
int age;
"
Pleased to meet you, Fiona!
String name; "
Your age in dog years is 178.5
"
Scanner scan = new Scanner(System.in); " fill in missing code
"
System.out.print("Enter your name and age:
);
name = scan.nextLine(); "
age = scan.nextInt(); "
"
"
System.out.println("Pleased to meet you, " + name + "!");"
System.out.println("Your age in dog years: " + age*10.5);
}"
} name = scan.nextLine();"
More examples see text: Echo.java
GasMileage.java
CSC 1051 M.A. Papalaskari, Villanova University