Terminal Input
Python |
Java |
The input function displays its argument as a prompt and
waits for input. When the user
presses the Enter or Return key, the function returns a string representing
the input text. The programmer
then either leaves the string alone or converts it to the type of data that
it represents (such as an integer). Input a line of text as
a string: name =
input("Enter your name: ") Input an
integer:
age =
int(input("Enter your age: "))
|
The Scanner class is used for the input of text and numeric
data from the keyboard. The
programmer instantiates a Scanner and uses the appropriate methods for each type
of data being input. Create a Scanner object attached to the keyboard: Scanner
keyboard = new Scanner(System.in); Input a line of text as
a string: String s =
keyboard.nextLine("Enter your name: "); Input an integer: int i =
keyboard.nextInt("Enter your age: "); Input a double: double d =
keyboard.nextDouble("Enter your wage: "); Caution: using the same scanner to input strings after numbers can result in logic errors. Thus, it is best to use separate
scanner objects for numbers and text. |