Page 46 - CTS - CSA TP - Volume 2
P. 46

COMPUTER SOFTWARE APPLICATION - CITS




           // Prompt the user to enter the second number
                   System.out.print(“Enter the second number: “);

                   // Read the second number from the user
                   double num2 = scanner.nextDouble();
                   // Close the Scanner to avoid resource leak
                   scanner.close();

                   // Calculate the sum of the two numbers
                   double sum = num1 + num2;
                   // Display the result
                   System.out.println(“The sum of “ + num1 + “ and “ + num2 + “ is: “ + sum);
               }

           }
           Output:

















           TASK 3: Reading Multiple Inputs with Scanner Class Example_3

           import java.util.Scanner;
           public class ScannerExample3 {
               public static void main(String[] args) {
                   Scanner scanner = new Scanner(System.in);

                   // Prompt the user to enter age and city
                   System.out.print(“Enter your age: “);
                   int age = scanner.nextInt();
                   // Consume the newline character left by nextInt
                   scanner.nextLine();
                   System.out.print(“Enter your city: “);

                   String city = scanner.nextLine();
                   // Display user information
                   System.out.println(“You are “ + age + “ years old and you live in “ + city);
                   // Close the Scanner

                   scanner.close();
               }
           }



                                                           31
 CITS : IT & ITES - Computer Software Application - Exercise 84  CITS : IT & ITES - Computer Software Application - Exercise 84
   41   42   43   44   45   46   47   48   49   50   51