Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

/* Chapter 3 Programming Activity 2 Calling class methods Anderson, Franceschi *

ID: 3808094 • Letter: #

Question

/* Chapter 3 Programming Activity 2 Calling class methods Anderson, Franceschi */ // ***** add your import statements here public class PracticeMethods { public static void main(String [] args) { //***** // 1. a. Create a Scanner object to read from the console // b. Prompt the user for their first name // c. Print a message that says hello to the user // d. Print a message that says how many letters // are in the user's name // Part 1 student code starts here: // Part 1 student code ends here. //***** // 2. a. Skip a line, then prompt the user for the year // they were born. // b. Calculate and print the age the user will be this year. // c. Declare a constant for average life expectancy, // set its value to 77.9 // d. Print a message that tells the user the percentage // of their expected life they've lived. // Use the DecimalFormat class to format the percentage // Part 2 student code starts here: // Part 2 student code ends here. //***** // 3. a. Generate a random integer between 1 and 20 // b. Pop up an input dialog box and ask the user for a guess. // c. Pop up an output dialog box telling the user the number // and how far from the number the guess was (hint: use Math.abs) // Part 3 student code starts here: // Part 3 student code ends here. } }

Explanation / Answer

import java.util.Random;
import java.util.Scanner;

import javax.swing.JOptionPane;


public class Part1 {
   static final double avgLifeExpectancy = 77.9;
   public static void main(String args[]){
       Scanner sc = new Scanner(System.in);
      
       System.out.print("Enter your first name: ");
       String name = sc.nextLine();
       System.out.println("hello! "+name);
       System.out.println("there are "+name.length()+" characters in your name");
      
      
       System.out.println();
       System.out.print("Enter your year of birth: ");
       int year = Integer.parseInt(sc.next());
       System.out.println("Your age is: "+(2017-year));
      
       double percent = (Math.abs(avgLifeExpectancy-(2017-year))/avgLifeExpectancy)*100;
       System.out.println("percentage of the expected life you'he lived: "+percent);
      
       int min=1,max=20;
       Random r = new Random();
       int Result = r.nextInt(max-min) + min;
       String test1= JOptionPane.showInputDialog("Guess any number between 1 and 20 : ");
       int test2 = Integer.parseInt(test1);
       if(Result==test2){
           JOptionPane.showMessageDialog (null, "Your guess is right" );
       }
       else if(Result>test2){
           JOptionPane.showMessageDialog (null, "Too low" );
       }
       else
           JOptionPane.showMessageDialog (null, "Too high" );
   }
}