Name: ________________________________________ Date: __________________
Section: _____________ Roll No.: _______________
La Martiniere Girls’ College
Class VIII
Computer Science
Chapter 1
Java Programming – Input in Java using Scanner Class
In Java, we often need to take input from users to make our programs more interactive. To achieve this,
we use a special tool called the Scanner class. The Scanner class is part of the java.util package and
allows us to read input from the keyboard.
Steps to use the Scanner class to input values –
1. To use the Scanner class, we first need to import it into our program.
2. We need to create a Scanner object which will be used to read input from the user.
Scanner sc = new Scanner(System.in);
i) Reading String Values - To read a string from the user, we use the next() method of the
Scanner class. It reads a single word (sequence of characters without spaces). If you want to
read a whole line, you can use nextLine() method.
Example:
String name = sc.next();
System.out.println("Hello, " + name + "!");
String line = sc.nextLine();
System.out.println("You entered: " + line);
ii) Reading Integer Values - To read whole numbers (integers), you can use the nextInt()
method of the Scanner class.
Example:
System.out.print("Enter your age: ");
int age = sc.nextInt();
System.out.println("You are " + age + " years old.");
iii) Reading Float Values - To read decimal numbers (floating-point values), you can use the
nextFloat() method.
Example:
System.out.print("Enter the temperature: ");
float temp = sc.nextFloat();
System.out.println("The entered temperature is: " + temp + " degrees Celsius");
LMGC/Cl 8/COMPUTER SCIENCE /Ch. No.1 Page 1 of 2
PROGRAM FLOWCHART
Accept the name of a student and her
marks in English and Mathematics. Find Start
the total marks scored by her. Print the
same.
import java.util.*; input name
class Marks input marks , e, m
{
public static void main (String args[])
{
String n; int e, m, t; t=e+m
Scanner sc=new Scanner(System.in);
System.out.println("Enter name");
n= sc.nextLine();
Display t
System.out.println("Enter marks of English
and Mathematics");
e = sc.nextInt();
m = sc.nextInt(); Stop
t = e+m;
System.out.print("Total marks scored by
"+n +" are "+t);
}
}
EXERCISES:
i. Write the above program in your exercise book.
ii. Draw the given flowchart on a punch sheet and colour them.
LMGC/Cl 8/COMPUTER SCIENCE /Ch. No.1 Page 2 of 2