Linked Questions

Popular Questions

The problem I have to solve is "Create a program that asks for the names and ages of two users. After that the program prints the sum of their ages." I've imported java.util*; and I couldn't find out where is the mistake?

import java.util.*;
public class Ex12 
{
     public static void main(String[] args) 
       {
         //input method
          Scanner scan1 = new Scanner(System.in);
         //first person's name and age
           System.out.print("Enter first person name : ");
           String firstPersonName = scan1.nextLine();
           System.out.print("Enter "+ firstPersonName+"'s age: ");
           int firstPersonAge = scan1.nextInt();
           scan1.close();

         //second person's age
           Scanner scan2 = new Scanner(System.in);
           System.out.println("Enter second person name : ");
           String secondPersonName = scan2.nextLine();
           System.out.print("Enter "+ secondPersonName+"'s age: ");
           int secondPersonAge = scan2.nextInt();
           scan2.close();

         //adding their ages
           int CombinedAge =  firstPersonAge + secondPersonAge;
           System.out.println("The Combined age of "+firstPersonName+" and "+secondPersonName+ " is: "+CombinedAge);
}}

Enter first person name : penny Enter penny's age: 21 Enter second person name : Exception in thread "main" java.util.NoSuchElementException: No line found at java.util.Scanner.nextLine(Scanner.java:1540) at Ex12.main(Ex12.java:16)

Related Questions