Question

Write a simple polling program that allows users to rate 5 issues from 1 (low importance)...

Write a simple polling program that allows users to rate 5 issues from 1 (low importance) to 10 (high importance). Use a one dimensional array of type String to store the five causes. Prompt for the number to be polled. Use a 5X(numPolled) int array to store the results of the survey,

but please prompt for the file name. When you run the program ask a user rate each issue. The five issues are Environment, War and Peace, Economy, Education, and Infrastructure. Read in the five causes from a file Repeat this process for tnumPolled users. If a user gives an out of range keep prompting the user until the user answers the question correctly.

Write the following outputs to a file (prompt for the name). Include the following:

  1. A tabular report with 5 topics down the left side and the results of the ratings for the numPolled users on the line as shown in the text file.
  2. To the right of each row show the average of the results to two decimal places.
  3. Determine which issue received the highest poll total and write out that cause and it’s poll average.
  4. Determine which issue received the highest poll total and write out that cause and it’s poll average.

Implementation Guidance.

You should implement the above program with the following methods:

main

Create a String array of causes called causesList..

Calls readCauses with no parameters, which returns a reference to a String array.

Requests number (numPolled) to be polled interactively.

Call performSurvey with the causesList and numPolled as parameters. This method returns a reference to a two dimensional int array with the pollResults. (Can call it pollResults in main)

Call calcCausesSums with pollResults as a parameter. Return a reference to a one-dimensional int array with the sums by row.(Can call it causesSum in main

Call calcAverage with reference to causesSum and the value of numPolled as parameters, returning a reference to a one-dimensional double array. (Can call it averageForCause)

Call reportResults with causesList, pollResults, averageForCause, causesSum references as parameters, and no return value.

readCauses with no parameters

readCauses sets up a Scanner and reads from a file the causes. The file format is one cause per line. You can hardcode in the number of causes as 5 causes for this example. Return a reference to a String array with the causes. You can use my causes.txt file.

performSurvey with the causesList reference and numPolled as parameters

Interactively request the importance for each pollee. Put the answers into a two dimensional int array and return a reference to it. Reject and request a new value for any value less than 1 or greater than 10See below for the possible format for the interactive questioning.

calcCausesSums with pollResults reference as parameter

Calculate the total for each row (cause) and return results in a one-dimensional int array.

calcAverage with causesSum reference and the value of numPolled as parameters

Calculate the average for each row and return a reference to a one dimensional array.

reportResults with causesList, pollResults, averageForCause, causesSum references as parameters

Interactively request an output file name, and create an output File and use PrintWriter to write to it.

Produce the output similar to that in my pollresults.txt file. The average must be printed to two decimal places.

Call findMaxCause with a reference to average as a parameter, returning an int of the array index with the highest average or the first with that average if all are the same.

Call findMinCause with a reference to average as a parameter, returning an int of the array index with the lowest average or the first with that average if all are the same.

Write out the last two lines to your file as shown in the pollresults.txt file.

findMaxCause and findMinCause each accept a reference to average and return the index as described above.

Output:

Polling Results

Cause           Polled Person    Average

                          1 2 3 4

Environment     5 10 1 1        4.25

War and Peace 6 9 10 7        8.00

Economy           7 4 5 9        6.25

Education         8 7 8 3        6.50

Infrastructure    3 7 3 10        5.75

The cause War and Peace with an average rating of 8.00 is the highest rated cause

The cause Environment with an average rating of 4.25 is the lowest rated cause

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

Dear Student,

Here is the code for your program.

CODE TO COPY -----

import java.nio.charset.StandardCharsets;

import java.io.*;

import java.util.*;

public class Polling{

public static void main(String[] args) {

Scanner in = new Scanner(System.in);

String [] causeList = new String[5];

causeList = readCauses();

System.out.println("Enter number of polls");

int numpoll = in.nextInt();

int [][] pollResults = new int[5][numpoll];

pollResults = performSurvey(causeList,numpoll);

int[] causesSum = calcCausesSums(pollResults);

double[] averageForCause = calcAverage(causesSum,numpoll);

reportResults(causeList, pollResults, averageForCause);

}

public static String[] readCauses(){

String[] causes = new String[5];

int i=0;

try {

Scanner scanner = new Scanner(new File("causes.txt"));

// Read lines from the file

while(scanner.hasNextLine()) {

causes[i]=scanner.nextLine();

i++;

}

scanner.close();

}

catch (FileNotFoundException e) {

e.printStackTrace();

}

return causes;

}

public static int[][] performSurvey(String[] causes, int num){

Scanner in = new Scanner(System.in);

int[][] results = new int[5][num];

for (int j=0;j<num;j++){

System.out.println("Enter ratings for importance\nPoll "+ (j+1));

for(int i=0;i<5;i++){

System.out.print(causes[i]+" ");

int value = in.nextInt();

if(value>0 && value <=10)

results[i][j]=value;

else{

System.out.println("Invalid rating. Please try again");

i--;

continue;

}

}

}

return results;

}

public static int[] calcCausesSums(int [][] results){

int col = results[0].length;

int[] sum= new int[5];

for(int i=0;i<5;i++){

for(int j=0;j<col;j++){

sum[i]+=results[i][j];

}

}

return sum;

}

public static double[] calcAverage(int [] sum,int num){

double[] avg= new double[5];

for(int i=0;i<5;i++){

avg[i]=sum[i]/num;

}

return avg;

}

public static void reportResults(String[] causes, int [][]results, double[] average)

{

int col = results[0].length;

System.out.println("Enter filename to save output with extension .txt");

Scanner in = new Scanner(System.in);

String filename = in.next();

File file = null;

try {

file = new File(filename);

/*If file gets created then the createNewFile()

* method would return true or if the file is

* already present it would return false

*/

boolean fvar = file.createNewFile();

if (fvar){

System.out.println("File has been created successfully");

}

else{

System.out.println("File already present at the specified location");

}

} catch (IOException e) {

System.out.println("Exception Occurred:");

e.printStackTrace();

}

  

// write data to file

try (PrintWriter out = new PrintWriter(file, StandardCharsets.UTF_8.name())) {

out.print("Polling Results\n");

out.print("Causes\tPolled Person\tAverage\n");

out.print("\t\t\t\t");

for(int i=0;i<col;i++)

out.print((i+1)+" ");

out.print("\n");

for(int i=0;i<5;i++){

out.print(causes[i]+"\t\t");

for (int j = 0;j<col;j++){

out.print(results[i][j]+"\t");

}

out.print(average[i]+"\n");

}

  

int min = findMinCause(average);

int max =findMaxCause(average);

  

String maxsentence = " The " + causes[max] + " with an average rating of " +average[max]+" is the highest rated cause";

String minsentence = " The " + causes[min] + " with an average rating of " +average[min]+" is the lowest rated cause";

out.print("\n"+maxsentence+"\n"+minsentence);

System.out.println("Successfully written data to the file");

} catch (IOException e) {

e.printStackTrace();

}

}

public static int findMaxCause(double[] average){

int index = 0;

double max=0;

for(int i=0;i<5;i++)

if(average[i]>max){

max=average[i];

index=i;

}

return index;

}

public static int findMinCause(double[] average){

int index = 0;

double min=average[0];

for(int i=0;i<5;i++)

if(average[i]<min){

min=average[i];

index=i;

}

return index;

}

}

-------

OUTPUT:

Please give me thumbs-up if you find this code useful.

Add a comment
Know the answer?
Add Answer to:
Write a simple polling program that allows users to rate 5 issues from 1 (low importance)...
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
  • Using basic c++ write 2 separate codes for this assignment. Program #1 Write a program that...

    Using basic c++ write 2 separate codes for this assignment. Program #1 Write a program that calculates the average of a group of test scores, where the lowest score in the group is dropped. It should use the following functions. • void getScore() should ask the user for a test score, store it in the reference parameter variable, and validate it. This function should be called by the main once for each of the five scores to be entered. •...

  • Document2 Tell me ign Layout References Mailings Review View 1. Write a program called Lab18C that...

    Document2 Tell me ign Layout References Mailings Review View 1. Write a program called Lab18C that searches for a number in an array. T a. Write a bool function named search that receives 3 parameters: an int array, an int containing the length of the array, and an int number to search for. Return true if the number is in the array and false otherwise. b. Write a void function called fillArray with the array as a parameter that uses...

  • c# Write compile and test a program named IntegerStatistics. The programs Main() method will: 1. Declare...

    c# Write compile and test a program named IntegerStatistics. The programs Main() method will: 1. Declare an array of 10 integers. 2. Call a method to interactively fill the array with any number of values (up to 10) until a sentinel value is entered. [If an entry is not an integer, continue prompting the user until an integer is entered.] When fewer than 10 integers are placed into the array, your statistics will be off unless you resize the array...

  • Write a menu based program implementing the following functions: (0) Write a function called displayMenu that...

    Write a menu based program implementing the following functions: (0) Write a function called displayMenu that does not take any parameters, but returns an integer representing your user's menu choice. Your program's main function should only comprise of the following: a do/while loop with the displayMenu function call inside the loop body switch/case, or if/else if/ ... for handling the calls of the functions based on the menu choice selected in displayMenu. the do/while loop should always continue as long...

  • The XYZ Company needs you to write a program that will allow them to enter the...

    The XYZ Company needs you to write a program that will allow them to enter the weekly sales for a salesperson and then the program will calculate things such as most sales (and what day on which they happened), least sales (and day on which they happened), total sales, and daily average. The program will need to do the following: • Validate the user input to ensure that it is not less than 0.0 (0.0 will be acceptable if there...

  • (Polling) The Internet and the web are enabling more people to network, join a cause, voice...

    (Polling) The Internet and the web are enabling more people to network, join a cause, voice opinions, and so on. Recent presidential candidates have used the Internet intensively to get out their messages and raise money for their campaigns. In this exercise, you’ll write a simple polling program that allows users to rate five social-consciousness issues from 1 (least important) to 10 (most important). Pick five causes that are important to you (e.g., political issues, global environ- mental issues). Use...

  • Submit Chapter7.java with four (4) public static methods as follows: A. Write a method called mostCommon...

    Submit Chapter7.java with four (4) public static methods as follows: A. Write a method called mostCommon that accepts an array of integers as its only parameter, and returns the int that occurs most frequently. Break ties by returning the lower value For example, {1,2,2,3,4,4} would return 2 as the most common int. B. Write mostCommon (same as above) that accepts an array of doubles, and returns the double that occurs most frequently. Consider any double values that are within 0.1%...

  • Write a complete program that uses the functions listed below. Except for the printOdd function, main...

    Write a complete program that uses the functions listed below. Except for the printOdd function, main should print the results after each function call to a file. Be sure to declare all necessary variables to properly call each function. Pay attention to the order of your function calls. Be sure to read in data from the input file. Using the input file provided, run your program to generate an output file. Upload the output file your program generates. •Write a...

  • 1. Write code for a function that receives two parameters (a,and b) by value and two...

    1. Write code for a function that receives two parameters (a,and b) by value and two more parameters (c and d) by reference. All parameters are double. The function works by assigning c to (a/b) and assigning d to (a*b). The function has no return value. From main, use scanf to get two numbers, then call the function, and then display both outcome values to the output in a printf statement. 2. After part 1 is completed, write code to...

  • Please help. I need a very simple code. For a CS 1 class. Write a program...

    Please help. I need a very simple code. For a CS 1 class. Write a program in Java and run it in BlueJ according to the following specifications: The program reads a text file with student records (first name, last name and grade). Then it prompts the user to enter a command, executes the command and loops. The commands are the following: "printall" - prints all student records (first name, last name, grade). "firstname name" - prints all students with...

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