Cl 8 - Ch 1- Java Programming 2024
Cl 8 - Ch 1- Java Programming 2024
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.
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");
e = sc.nextInt();
m = sc.nextInt(); Stop
t = e+m;
}
}
EXERCISES:
i. Write the above program in your exercise book.
ii. Draw the given flowchart on a punch sheet and colour them.