During runtime of a computer program, the program can ask the user to input data, read the user’s input, and then show the user an output result. Scanner is the tool we use to implement the user interaction feature on the console window.
Importing java.util.Scanner
Approach 1. Add line import java.util.Scanner; at the top of your Java code, and then add the following in your main() class:
Approach 2. Type code Scanner input = new Scanner(System.in); in your Java code directly, and then use Eclipse’s IntelliSense to choose the right fix. In other words, Eclipse will suggest that you add the import statement because it spots that you might need it.
As a result, import java.util.Scanner; will be added at the top of the class.
Getting Input
nextLine(): read a string input
next(): read a string input
nextInt(): read an integer input
nextFloat(): read a float number input
next() reads the input only until the space.
It cannot read two words separated by a space. And it places the cursor at the same line after reading the input stream, meaning it doesn’t change the line.
nextLine() reads the input until the end of the line (‘ ’).
It will automatically move the scanner down after returning the current line.
Producing Output
System.out.println is a common way to display text in the console window. Developers often use it to read a user’s input, provide general information to the user, and log information (to the console) during runtime in order to find out what is going on with key variables.
+: concatenates two strings;
: a newline character;
: a tab key character that aligns text at the tab width;
\: a backslash character;
: a carriage return character;
" and ": double quote characters.
Lab Work
- 1.
display the string concatenation between two substrings “I am” and “a developer” using +
- 2.
display a new line
- 3.
display quotes using " and "
Example
- 1.
System.out.println("Hello, world!");
- 2.
System.println.out('Hello, world!');
- 3.
System.println("Hello, world!");
- 4.
System.println(Hello, world!);
- 5.
Out.system.println"(Hello, world!)";
Answer: 1
Example
Lab Work
Problems
- 1.What is the output produced from the following statements?System.out.println("name age height");System.out.println("Anthony 17 5'9"");System.out.println("Belly 17 5'6"");System.out.println("Bighead 16 6'");
- 2.What is the output produced from the following statements?System.out.println(" a b c");System.out.println("\\");System.out.println("'");System.out.println(""""");
- 3.Write a program in Java to print the following:/\//\///