4.1.9 Identify the inputs and outputs required in a solution.
An output stream sends data to an output device. The System class with methods for displaying output. For displaying data to the standard output stream, which are:
displays data and leaves the insertion point at the end of the output
moves the insertion point to the next line after displaying output.
public class MulticulturalGreeting {
public static void main(String[] args) {
System.out.print("Hello");
System.out.print("Buenos Dias");
System.out.println("Bonjour");
System.out.println("How do you greet another?");
}
}
HelloBuenos DiasBonjour
How do you greet another?
An escape sequence is a backslash (\) followed by a symbol that together represent a character. Escape sequences are used to display special characters.
\n newline
\t tab (8 spaces)
\\ backslash
\" double quotation mark
public static void main(String[] args) {
System.out.print("Hello\t");
System.out.print("Buenos Dias\t");
System.out.println("Bonjour");
System.out.println("How do you greet another?");
}
Hello Buenos Dias Bonjour
How do you greet another?
Scanner input = new Scanner(System.in);
input.next(); // input of a single word
input.nextLine(); // input of multiple words
input.nextInt(); // input of an integer
input.nextDouble(); // decimal number input
The next() method should be used for reading string data after numeric data has been read.
If the nextLine() method is used, the end-of-line character left by the numeric entry is read and any text typed is ignored.
System.out.print("Enter age: ");
age = input.nextInt();
System.out.print("Enter first name: ");
firstName = input.next();
System.out.println("Welcome, "+firstName+"! you are "+age+" years old.");
Enter age: 12
Enter first name: John
Welcome, John! you are 12 years old.
Alternatively, a statement can be added to read the end-of-line character left by the numeric entry, so that the nextLine() method can be used to read a string that may contain white space:
System.out.print("Enter age: ");
age = input.nextInt();
input.nextLine(); //removes end-of-line
System.out.print("Enter full name: ");
fullName = input.nextLine();
System.out.println("Hello, "+age+ " year-old "+fullName+"!");
Enter age: 34
Enter full name: John Lewis
Hello, 34 year-old John Lewis!