Page 329 - CITS - Computer Software Application -TT
P. 329
COMPUTER SOFTWARE APPLICATION - CITS
// Declare the object and initialise with
// predefined standard input object
Scanner sc = new Scanner(System.in);
// String input
String name = sc.nextLine();
// Character input
char gender = sc.next().charAt(0);
// Numerical data input
// byte, short and float can be read
// using similar-named functions.
int age = sc.nextInt();
double cgpa = sc.nextDouble();
// Print the values to check if the input was
// correctly obtained.
System.out.println(“Name: “ + name);
System.out.println(“Gender: “ + gender);
System.out.println(“Age: “ + age);
System.out.println(“CGPA: “ + cgpa);
}
}
1 It imports the Scanner class to facilitate user input.
2 In the main method:
• It creates a Scanner object sc to read input from the standard input stream (System.in).
• It uses sc.nextLine() to read a line of input as a String and stores it in the name variable.
• It uses sc.next().charAt(0) to read the next token (word) as a String and then extracts the first character of
that string as a char, storing it in the gender variable.
• It uses sc.nextInt() to read the next token as an int and stores it in the age variable.
• It uses sc.nextDouble() to read the next token as a double and stores it in the cgpa variable.
3 After reading all the values, it prints them to the console to verify that the input was correctly obtained.
Input
AKASH MOHAN
Male
24
91
Output
Name: AKASH MOHAN
Gender: M
Age: 24
CGPA: 91.0
316
CITS : IT&ITES - Computer Software Application - Lesson 78 - 84