Object-Oriented Programming with Java, part I – Exercise 12

Exercise 12

This program asks for two names and ages and then outputs them in a string with the ages added together.

My code

import java.util.Scanner;

public class SumOfTheAges {

    public static void main(String[] args) {
        Scanner reader = new Scanner(System.in);

        // Implement your program here
        System.out.print("Type your name: ");
        String name1 = reader.next();
        
        System.out.print("Type your age: ");
        int age1 = Integer.parseInt(reader.next());
        
        System.out.println("");
        
        System.out.print("Type your name: ");
        String name2 = reader.next();
        
        System.out.print("Type your age: ");
        int age2 = Integer.parseInt(reader.next());
        
        System.out.println("");
        
        System.out.println(name1 +" and " + name2 + " are " + (age1 + age2) +" years old in total.");
        
    }
}

Model code

import java.util.Scanner;

 

public class SumOfTheAges {

 

    public static void main(String[] args) {

        Scanner reader = new Scanner(System.in);

 

        // Implement your program here

        System.out.print("Type your name: ");

        String nameOfTheFirst = reader.nextLine();

        System.out.print("Type your age: ");

        int ageOfTheFirst = Integer.parseInt(reader.nextLine());

 

        System.out.println(""); 

        System.out.print("Type your name: ");

        String nameOfTeSecond = reader.nextLine();

        System.out.print("Type your age: ");

        int ageOfTheSecond = Integer.parseInt(reader.nextLine());

 

        System.out.println(""); 

         

        System.out.println(nameOfTheFirst + " and " + nameOfTeSecond + " are" + (ageOfTheFirst + ageOfTheSecond) + 

                " years old in total.");

    }

}
Leave a Reply

Your email address will not be published. Required fields are marked *