Question

Hello. I am using a Java program, which is console-baed. Here is my question. Thank you....

Hello. I am using a Java program, which is console-baed.

Here is my question. Thank you.

1-1

Write a Java program, using appropriate methods and parameter passing, that obtains from the user the following items: a person’s age, the person’s gender (male or female), the person’s email address, and the person’s annual salary. The program should continue obtaining these details for as many people as the user wishes.

As the data is obtained from the user

  • validate the age to ensure that the value lies in the range 20 to 30 inclusive; you may assume that the user will enter whole numbers only.

  • validate the salary to ensure that it lies in the range 40000 to 150000 inclusive; you may assume that the user will enter whole numbers only.

  • write the data to a text file named salaries.txt in the following format: age; gender; email address; salary

    Note: each line of data represents one person and each data value is separated by a semicolon (;). Hence the data in the file that you create would look similar to:

                22;male;brad#gmil.com;65000
                20;female;lucy#icloud.com;72000
                21;female;angela.Samson#yahoo.com.au;51000
                23;female;m_king#me.com;125000
    

(# = @)

  • When the program terminates it should display to the screen how many of the people were male and how many were female that were written to the file.

1-2

  1. A file named loanBalance.txt contains numeric values that represent the balance of home loans for customers of a bank. The loan balance for each customer is on a separate line within the file. Example data from the file might be similar to:

    65340.50
    43892.00
    38102.95
    89820.75
    106530.60
    

    Your Java program must

    • read the file into an appropriate array – you may assume that the file exists. The array should be sized to store 500 loan balances but keep in mind that the file may not contain 500 loan balances.

    • after reading the file into the array, calculate and display the average (mean) of the loan balances

      from the array.

    • after reading the file into the array, determine and display the largest loan balance from the array.

    • use appropriate methods and parameter passing.

0 0
Add a comment Improve this question Transcribed image text
Answer #1

//Solution 1

//Java code

import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.Scanner;

public class Main {
    public static void main(String[] args) throws FileNotFoundException {
        int age;
        String gender;
        String email;
        int annualSalary;
        //Open file to write data
        PrintWriter writer = new PrintWriter("salaries.txt");
        Scanner input  = new Scanner(System.in);
        char choice=' ';
        int maleCounter=0,femaleCounter=0;
        do {
            System.out.print("Enter person's age: ");
            age = input.nextInt();
            /**
             * validate the age to ensure that the
             * value lies in the range 20 to 30
             */
            while (age<20 || age>30)
            {
                System.err.println("Please enter valid age (20 - 30).");
                System.out.print("Enter person's age: ");
                age = input.nextInt();
            }
            System.out.print("Enter person's gender: ");
            gender = input.next();
            if(gender.equalsIgnoreCase("male"))
                maleCounter++;
            else
                femaleCounter++;
            System.out.print("Enter person's emailId: ");
            email = input.next();
            System.out.print("Enter person's salary: ");
            annualSalary = input.nextInt();
            while (annualSalary<40000 || annualSalary>150000)
            {
                System.err.println("Please enter valid salary(40000 - 150000).");
                System.out.print("Enter person's salary: ");
                annualSalary = input.nextInt();
            }
            //write data to file
            writer.println(age+";"+gender+";"+email+";"+annualSalary);
            System.out.print("Do you want to continue (y/n): ");
            choice = input.next().toLowerCase().charAt(0);
        }while (choice=='y');
        //close the stream
        writer.close();
        System.out.println("\nNumber of females written to file: "+femaleCounter);
        System.out.println("Number of males written to file: "+maleCounter);
    }
}

//salaries.txt

Main.java * salaries.txt $2;male; brad#gmil.com; 65000 20; female; lucy#icloud.com;72000

//Output

C:\Program Files\Java\jdk1.8.0_221\bin\java.exe ... Enter persons age: 22 Enter persons gender: male Enter persons email

//Solution 2

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class Loan {
    public static void main(String[] args)
    {
        /**
         *  The array should be sized to store 500 loan balances
         *  but keep in mind that the file may not contain 500
         *  loan balances.
         */
        double[] loans = new double[500];
        int counter =0;
        try {
            //open the file
            Scanner scanfile = new Scanner(new File("loanBalance.txt"));
            while (scanfile.hasNextDouble())
            {
                loans[counter]= scanfile.nextDouble();
                counter++;
            }
            //print stats
            System.out.println("Average of Loans: "+getAverage(loans,counter));
            System.out.println("Largest Loan: "+getLargestLoanBalance(loans,counter));


        }
        catch (FileNotFoundException e)
        {
            System.err.println("File not found.");
        }
    }
    private static double getAverage(double[] loans, int size)
    {
        double  sum=0,avg;
        for (int i = 0; i <size ; i++) {
            sum+=loans[i];

        }
        avg = sum/size;
        return avg;
    }
    private static double getLargestLoanBalance(double[] loans, int size)
    {
        double max = loans[0];
        for (int i = 0; i <size ; i++) {

            //find largest loan
            if(max<loans[i])
                max = loans[i];
        }
        return max;
    }
}

//Files

loanBalance.txt in.javax 65340.50 43892.00 38102.95 89820.75 106530.60

//Output

C:\Program Files\Java\jdk1.8.0_221\bin\java.ex Average of Loans: 68737.36000000002 Largest Loan: 106530.6 Process finished w

//If you need any help regarding this solution .......... please leave a comment ......... thanks

Add a comment
Know the answer?
Add Answer to:
Hello. I am using a Java program, which is console-baed. Here is my question. Thank you....
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • Help in Java please: This is not meant to be a program that compiles and runs....

    Help in Java please: This is not meant to be a program that compiles and runs. I only need program segments. DO NOT submit a complete Java file with documentation and other content. Write the statements (NOT an entire program) to: Ask the user for the number of students in a classroom. Validate the number of students to make sure it’s a positive value. NOTE: positive numbers are numbers greater than 0. Define an array named stud that can hold...

  • JAVA Using the data provided in the attachment, create a program that will display a child's...

    JAVA Using the data provided in the attachment, create a program that will display a child's predicted adult height. This program will need to create an array of objects to search. This program needs to validate the input for valid range and input values. If invalid data is given, the program needs to indicate that data is invalid and suggest appropriate values/ranges. However, you do not need to validate alphabetic data given for numeric input. 1. The program will need...

  • Description: This Java program will read in data from a file students.txt that keeps records of...

    Description: This Java program will read in data from a file students.txt that keeps records of some students. Each line in students.txt contains information about one student, including his/her firstname, lastname, gender, major, enrollmentyear and whether he/she is a full-time or part-time student in the following format. FIRSTNAME      LASTNAME        GENDER              MAJORENROLLMENTYEAR FULL/PART The above six fields are separated by a tab key. A user can input a keyword indicating what group of students he is searching for. For example, if...

  • Homework 3: Input Validation 1   Objectives control structures console-based user input using Scanner class writing complete...

    Homework 3: Input Validation 1   Objectives control structures console-based user input using Scanner class writing complete programs using two classes: client and supplier 2   User Interface Specification This is a console-based I/O program. Display should go to System.out (print or println) and the program will get user input using the Scanner class. The flow of execution should be as follows: When the program starts, display a one-line introduction to the user Display a menu with 5 options 1. validate zip...

  • IN PYTHON ONLY I am looking for 4 columns, Age, Gender, Ideal Age of a Spouse,...

    IN PYTHON ONLY I am looking for 4 columns, Age, Gender, Ideal Age of a Spouse, and the message. I will have 6 rows in the table, and 4 columns, followed by  averages. Calculate the ideal age of a spouse. Enter either m or f from the keyboard in lower case. You may use string data for the gender. Convert the gender to upper case Enter an age from the keyboard, probably an integer You will need prompts telling the user...

  • IN PYTHON ONLY I am looking for 4 columns, Age, Gender, Ideal Age of a Spouse, and the message. I will have 6 rows in th...

    IN PYTHON ONLY I am looking for 4 columns, Age, Gender, Ideal Age of a Spouse, and the message. I will have 6 rows in the table, and 4 columns, followed by  averages. Calculate the ideal age of a spouse. Enter either m or f from the keyboard in lower case. You may use string data for the gender. Convert the gender to upper case Enter an age from the keyboard, probably an integer You will need prompts telling the...

  • Language: Java 30 pts. ) - This assignment revisits the student parsing program from earlier in...

    Language: Java 30 pts. ) - This assignment revisits the student parsing program from earlier in the quarter, but challenges you to restructure the component pieces of the program to create a cleaner, more succinct Main(). You will generate a Student class of object and load an Array List with student objects, then report the contents of that Array List. To do so, you must perform the following: A)(10 /30 pts.)- Generate a class file “myStudent.java” (which will generate myStudent.class...

  • In this assignment you will practice using Data Structures and Object Oriented concepts in Java. Your implementation should target the most efficient algorithms and data structures. You will be graded...

    In this assignment you will practice using Data Structures and Object Oriented concepts in Java. Your implementation should target the most efficient algorithms and data structures. You will be graded based on the efficiency of your implementation. You will not be awarded any points if you use simple nested loops to implement the below tasks. You should use one or more of the below data structures: - ArrayList : - JavaDoc: http://docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html - Tutorial: http://docs.oracle.com/javase/tutorial/collections/interfaces/list.html Question You are provided with...

  • USING JAVA Write a program for calculating body fat and body fat percentage. The following simple...

    USING JAVA Write a program for calculating body fat and body fat percentage. The following simple formulas will be used for our calculations Body fat formula for female: A1 = (weight * .732) + 8.987 A2 = wrist measurement / 3.14 A3 = waist measurement * .157 A4 = hip measurement * .249 A5 = forearm measurement * .434 B = A1 + A2 - A3 – A4 + A5 Body fat = weight – B Body fat percentage =...

  • In Java Code Needed is Below the Question Using Program 3: Encapsulating Dogs, modify this program...

    In Java Code Needed is Below the Question Using Program 3: Encapsulating Dogs, modify this program to create a database of dogs of your own. You will also include File I/O with this program. You will create 3 classes for this assignment. The first class: Create a Class representing the information that is associated with one item (one dog) of your database. Name this class Dog. Using Lab 3, this will include the information in regard to one dog. The...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT