Professor Abdul-Quader
Input/Output
The current time is 12:30.
The current time is 12:30.
In 55 minutes, it will be 13:25.
The char data type represents single characters. A single character literal is written with single quotes around it.
The String data type can be used to represent longer text. String literals are written with double quotes around them.
Strings can be concatenated with the + operator:
Strings can be concatenated with data of other types:
This can cause some confusion. Java reads the operation left-to-right. Can you guess what is outputted in the following two lines?
System
class.System.out
is a variable inside the System
class.PrintStream
.
PrintStream
has several methods for outputting, including println
and printf
.System.out
.We can also view information about Java standard libraries online: search for “java PrintStream” for example.
We use the Scanner
class for input:
Write a program that asks a user to input their height in inches, and then displays their height in standard form (feet and inches).
For example, if the user types in 70, we should convert that to 5’10".
hasNextInt may be useful for us in combination with if and while statements
Scanner sc = new Scanner(System.in);
System.out.println("Enter your age: ");
int age = sc.nextInt();
System.out.println("Enter your name: ");
String name = sc.nextLine();
System.out.println("Hi " + name + ", you are " + age + " years old!");
What happens?
Fix? Call nextLine after every group of nextInts.
All code goes inside a method!
Write a program that prompts a user for the amount of money they make per hour and the number of hours they worked, and outputs how much money they made in those hours. For the sake of simplicity, you can assume that the rate and the number of hours are integers.
What does the following code snippet do?
Scanner sc = new Scanner(System.in);
System.out.println("n?");
int n = sc.nextInt();
int x = 1;
for (int i = 0; i < n; i++) {
x *= 2;
}
System.out.println(x);
Make a memory diagram to figure it out.