What is wrong here? It's not printing test scores in descending order, nor am I getting a value for mean. Shows up 0.0
Her are the instructions that I was given:
This class will allow a user to enter 5 scores into an array. It will then rearrange the data in descending order and calculate the mean for the data set.
Attributes:
• data[]—the array which will contain the scores
• mean—the arithmetic average of the scores
Methods:
• Average—the constructor. It will allocate memory for the array. Use a for loop to repeatedly display a prompt for the user which should indicate that user should enter score number 1, score number 2, etc. Note: The computer starts counting with 0, but people start counting with 1, and your prompt should account for this. For example, when the user enters score number 1, it will be stored in indexed variable 0. The constructor will then call the selectionSort and the calculateMean methods.
• calculateMean—this is a method that uses a for loop to access each score in the array and add it to a running total. The total divided by the number of scores (use the length of the array), and the result is stored into mean.
• toString—returns a String containing data in descending order and the mean.
• selectionSort—his method uses the selection sort algorithm to rearrange the data set from highest to lowest.
import java.util.Scanner;
public class Average
{
private int[] data;
private double mean;
private int total = 0;
public Average()
{
data = new int[5];
Scanner keyboard = new Scanner(System.in);
for(int i = 0; i < data.length; i++)
{
System.out.print("Enter score number " + (i + 1) + ": ");
data[i] = keyboard.nextInt();
}
}
public void calculateMean()
{
int i, s = 0;
for(i = 0; i < data.length; i++)
{
s = s + data[i];
}
mean = (double)s / (data.length);
}
public void selectionSort()
{
int maxIndex;
int maxValue;
for(int startScan = 0; startScan < data.length - 1; startScan++)
{
maxIndex = startScan;
maxValue = data[startScan];
for(int index = startScan + 1; index < data.length; index++)
{
if(data[index] > maxValue)
{
maxValue = data[index];
maxIndex = index;
}
}
data[maxIndex] = data[startScan];
data[startScan] = maxValue;
}
}
public String toString()
{
String output;
output = "The test scores in descending order are \n";
for(int i = 0; i < data.length; i++)
{
output = output + data[i] + " ";
}
output = output + "\nThe average is " + mean;
return output;
}
}
You need methods that return and take in values with your methods. Here is a little mock-up of your program to show what I mean:
public static void main(String... args)
{
System.out.println(calculateMean(getData()));
}
public static int[] getData()
{
data = new int[5];
Scanner s = new Scanner(System.in);
for (int i = 0; i < data.length; i++)
{
System.out.print("Enter score number " + (i++) + ": ");
data[i] = Integer.parseInt(s.nextLine());
}
s.close();
return data;
}
public static double calculateMean(int[] data)
{
int s = 0;
for (int i = 0; i < data.length; i++)
{
s += data[i];
}
return mean = (double) s / (data.length);
}
The getData() method gets all the information we need from the user, and then we take that data and we pass it right along to the calculateMean() method. This, in turn, spits out the average of all the scores for us. Then all we do is print that. I'll leave the rest up to you since this looks like homework.
Trial run:
Input: 4, 67, 3, 7, 3 (comma's indicate new line)
Output: 16.8
All you need is
public static void main(String[] args){
Average avg = new Average();
avg.selectionSort();
avg.calculateMean();
System.out.println(avg);
}
Everything is in place. I second #HeatfanJohn
It looks like you are not executing the calculateMean() method call first like that:
public static void main(String[] args) {
Average average = new Average();
average.calculateMean();
average.selectionSort();
System.out.println(average.toString());
}
You never make a call to calculateMean(), that is why the average is zero. In you main or where ever you create your instance of Average, you need to call calculateMean() before referencing Average.toString().
Related
While running this code I am getting ArrayIndexOutOfBoundsException.
public class Evensum {
public static void main(String[] args) {
int num = Integer.parseInt(args[0]);
int even[] = new int[num];
int sum = 0,j = 0;
String evennums = "";
//Insert your code here
for(j=0; j<=num; j++) {
if(num%2==0) {
even[j]=num;
sum=sum+num;
args[j]= Integer.toString(num);
}
evennums=String.join(",", args);
}
System.out.println(evennums);
System.out.println(sum);
}
}
for (j=0; j<=num; j++)
This is wrong. It should be:
for (j = 0; j < num; j++)
Why? Assume num is 5. Before this line you initialized even to 5. The indices of even would be 0, 1, 2, 3, 4.
Now, with j<=num, you are trying to access the index 5, which does not exist and hence the exception.
args[j]= Integer.toString(num);
This line will raise another exception. I am assuming you're only passing one parameter from the command line which is args[0]. This means the args array is of size 1 and you cannot add more elements to it.
Also, it is not a good practice to add/modify elements to the args array. You should create a new array for this.
Please find the much simpler version of the Code by avoiding the Integer.toString and String.join to pass on the Arguments. Simple Integer Arraylist and adding the elements to will do the Trick.
package com.umapathy.java.learning.programs;
import java.util.ArrayList;
import java.util.List;
public class EvenSum
{
public static void main(String[] args)
{
int num = 20; //Initialize the user-defined value for the loop execution
int sum = 0 ; //Initialize the Sum Value as 0
List<Integer> evenlist = new ArrayList<Integer>(); //Define an integer
Array list
for (int i=2; i<=num; i++) //Begin the loop from the value of 2
{
if(i%2==0) //Logic to find whether a given number is Even Number or not
{
sum = sum + i; // If the logic returns true, Calculate the Sum Value
evenlist.add(i); // Add the Integer to the previous defined Integer
// Arraylist by calling add method
}
}
System.out.println(evenlist); // Print the Output outside the loops
System.out.println(sum);
}
}
Output Generated as follows:--
[2, 4, 6, 8, 10, 12, 14, 16, 18, 20] 110
package javaApp;
public class EvenSum {
public static void main(String[] args) {
int num = 20;
int even[] = new int[num];
int sum = 0,j = 0;
String evennums = "";
for(j=1; j<=num; j++) {
if(j%2==0) {
sum=sum+j;
evennums=evennums+","+j;
}
}
evennums=evennums.replaceFirst(",","");
System.out.println(evennums);
System.out.println(sum);
}
}
Why initialized the even array size if its actual length is unknown in initially. It's better to go with ArrayList in this case which have characteristic to grow dynamically.
Try in this way
public static void main(String[] args) {
int num = Integer.parseInt(args[0]);
List<Integer> evens = new ArrayList<Integer>();
int sum = 0;
for (int j = 0; j <= num; j++) {
if (j % 2 == 0) {
sum += j;
evens.add(j);
}
}
System.out.println("Even Numbers List : "+evens);
System.out.println("Total Sum : "+sum);
// If you want an array of int instead of ArrayList you can convert ArrayList into int[] with following two lines
int evenArray[] = even.stream().mapToInt(x->x).toArray();
System.out.println("Even Numbers Array : "+evenArray);
}
public static void main(String[] args) {
// TODO Auto-generated method stub
//System.out.println("Args: "+args[0]);
int num = Integer.parseInt(args[0]);
int even[] = new int[num];
int sum = 0,j = 0;
String evennums = "";
//Insert your code here
for(j=0; j<=num; j++) {
if(j%2==0) {
//even[j]=num;
sum=sum+j;
if(j!=0) evennums=evennums+","+j;
}
}
evennums=evennums.substring(1);
System.out.println(evennums);
System.out.println(sum);
}
At time of running in eclipse follow below steps:
Right click on class--> Run AS --> Run Configuration
Go to Arguments tab and pass value as 10
Click Run
Output:
2,4,6,8,10
30
The given program compiles, but doesn't run the way I want it though. I think it's not applying the methods I wrote. any ideas?
import java.util.Scanner;
public class Assignment_1_q1 {
static Scanner input = new Scanner(System.in);
public static int i;
public static int counter;
public static int n;
//main method
public static void main(String[] args) {
System.out.println("Enter n's value: " );
n = input.nextInt(); //Prompts the user to input the integer number n.
int[] table = new int[10]; //Create an array of size 10.
getArrayValues(table); //Calls the first method
matchCriteria(table, counter, n); //Calls the second methods
System.out.println("There is "+ n +"numbers greater than n!" ); //display the result.
}
//the first method to input array values from the user,
//allows nonnegative numbers only to be stored into the array.
public static int[] getArrayValues(int table[]){
while (table[i] < 0)
System.out.println("Pleas try a nonnegative number!" );
for (int i = 0; table[i] < table.length; i++){
System.out.println("Enter an array value: ");
table[i] = input.nextInt();
}
return table;
}
// the second method determines how many of array values are greater than the value of n.
public static int matchCriteria(int array[], int counter, int n){
counter = 0;
for(int i = 0; i < array.length && i > n;) {
if (i > n) counter++;
}
return counter;
}
}
You need to store the result of getArrayValues() to table as such:
table = getArrayValues(table);
int newcounter = matchCriteria(table, counter, n);
On top of that, realize your for loop is using table[i] instead of i in the selection criteria. it would be better to do it in a while loop:
Consider refactoring as such:
for (int i = 0; i < table.length; i++){
System.out.println("Enter an array value: ");
table[i] = input.nextInt();
while(table[i] < 0) {
System.out.println("Pleas try a nonnegative number!" );
table[i] = input.nextInt();
}
}
Like Elliott said, you aren't really doing anything with the data from invoking the methods. You have to use that depending on what you're trying to do.
So the purpose of my program is to create an array for 5 Salespeople. The user is prompted to enter in the total sales for each Person. Then, I need to print out the sum, average, lowest sale and highest sale. I can get the average, the sum of all the sales, and have managed to print the largest value of the array, but I need it to say, for example, Salesperson 2 had $50,000 in sales. What I have now is "50,000 had $50,000" if that makes since. So value 3 of the array (salesperson 2, as I have not included a Salesperson 0) is 50,000. My array:
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
final int SALESPEOPLE = 6;
int[] sales = new int[SALESPEOPLE];
int sum;
for (int i = 1; i < sales.length; i++) {
System.out.print("Enter sales for salesperson " + i + ": ");
sales[i] = scan.nextInt();
}
}
And the get max value
for (int i = 1; i < sales.length; i++) {
System.out.println(i + " \t" + sales[i]);
sum += sales[i];
}
System.out.println("The highest sale was");
int maxValue = getMaxValue(sales);
int maxValueName = getMaxValueName(sales);
System.out.println("Name: " + maxValueName + "Sale: " + maxValue);
System.out.println("The lowest sale was");
int minValue = getMinValue(sales);
System.out.println(minValue);
Max Value
public static int getMaxValue(int[] array) {
int maxValue = array[1];
for (int i = 1; i < array.length; i++) {
if (array[i] > maxValue) {
maxValue = array[i];
}
}
return maxValue;
}
public static int getMaxValueName(int[] array) {
int maxValueName = array[1];
for (int i = 1; i < array.length; i++) {
if (array[i] > maxValueName) {
maxValueName = array[i];
}
}
return maxValueName;
}
You have some number of personnel in your sales force. Each of these persons has a name and also has made some amount of sales (some sort of a number). So it makes no sense to store just a number in your array.
Define a type of object that contains a String (for a person's name) and a number (for how much they sold). That is the kind of object you should put in your array. It makes no sense to write in Java and then not use anything that has even a hint of object-oriented design about it.
Notice that once you have an array of these objects, if you can find the object that has the highest sales number then you also have found the one that has the name of the person you want to print. Now ask yourself why you would want to write two separate functions, each of which has to search the array to find that object.
I'm relatively new to the world of OOP, and for some reason, the console of IntelliJ and Eclipse doesn't give me an output in the console for the following program. I'm trying to store 12 numbers into an array using scanner and to find the standard deviation, mean, lowest number, and highest number. Can anyone spot what's wrong?
import java.util.Arrays;
import java.util.Scanner;
public class untitled
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
int[] grades = new int[12];
int size = grades.length;
for (int i = 0; i < size; i++)
{
grades[i] = in.nextInt();
}
Arrays.sort(grades);
int low = grades[0];
int high = grades[11];
int sum = 0;
for (int i: grades)
{
sum += i;
}
int m = sum / size;
double var = 0;
double variance;
double sd;
for (int i = 0; i < size; i++)
{
var = var + ((grades[i] - m) * (grades[i] - m));
}
variance = (int) var / size;
sd = Math.pow(variance,.5);
String lowest = ("Lowest Grade:" + low);
String highest = ("Highest Grade:" + high);
String average = ("Average Grade:" + m);
String standdev = ("Standard Dev.:" + sd);
System.out.println(lowest);
System.out.println(highest);
System.out.println(average);
System.out.println(standdev);
}
}
Thanks.
What you have done is to accept 12 inputs.. try entering 12 inputs in console and then your output will appear..
And yeah this doesnt seem to use OOP concepts. Please refer this link for more info regarding OOPS :
http://en.wikipedia.org/wiki/Object-oriented_programming
The problem is, that you need to enter values first, before the calculation and output can continue. Without having some printed text on the console (like "Enter a new number: ") the console will just stay empty.
You could either enter 12 numbers, or fill the list automatically with Random values. In this case the output will immediately be visible on the console.
...
nt[] grades = new int[12];
int size = grades.length;
Random random = new Random();
for (int i = 0; i < size; i++) {
grades[i] = random.nextInt(15); // value between 0 and 14
}
Arrays.sort(grades);
int low = grades[0];
...
I have six tasks that need to be completed but i do not know how to display them. I haave all the code to calculate each task needed but when it comes to applying them to my tester class i am stuck. below is my code for the original class. these are the task that need to be done:
Display the original data set, as shown in the table.
The average profit for the supermarket chain.
The city with the highest profit.
A list of all the cities with profit at, or above the average.
The cities and their profit listed in descending order of the profits.
Make a horizontal graph showing the performance of each supermarket
Please help because ive been doing this for the last couple days and still havent been able to do anything... i must be stupid please help
package supermarkets;
public class Supermarkets
{
private String[] city = {"Miami", "Sunrise", "Hollywood",
"Tallahassee", "Jacksonville", "Orlando", "Gainesville", "Pensacola",
"Ocala", "Sebring"};
private double[] profit = {10200000, 14600000, 17000000, 6000000,
21600000, 9100000, 8000000, 12500000, 2000000, 4500000};
public Supermarkets(String[] c, double[] p)
{
//array for the city
city = new String[c.length];
for (int i = 0; i < c.length; i++)
city[i] = c[i];
//array for the profits
profit = new double[p.length];
for(int i = 0; i < p.length; i++)
profit[i] = p[i];
}
//sums up the profits from the cities
public double sumArray()
{
double sum = 0;
for (int i = 0; i < profit.length; i++)
sum = sum + profit [i];
return sum;
}
//calculates the average of the profits from the cities
public double average()
{
return sumArray() / profit.length;
}
//shows highest profit
double findHighestProfit()
{
double highest = profit[0];
for(int i = 1; i < profit.length; i++)
{
if ( profit [i] > highest )
highest = profit [i];
}
return highest;
}
//gives the above average profit
public String aboveAvarage()
{
String s = "";
double avg = average();
for (int i = 0; i < profit.length; i++)
if (profit [i] > avg)
s = s + city[i] + " " + profit[i] + "\n";
return s;
}
//creates a graph showing city and profits
public String makeGraph()
{
String s = "";
for (int i = 0; i < profit.length; i++)
{
s = s + city[i] + " ";
int x = (int) Math.floor( profit[i] );
for(int j = 1; j <=x; j++)
s = s + "*";
s = s + "\n";
}
return s;
}
//resets profits position from least to greatest
public int findPosition(int startScanFrom)
{
int position = startScanFrom;
for (int i = startScanFrom + 1; i < profit.length; i++)
if (profit[i] < profit[position])
position = i;
return position;
}
//swaps values for city and profits
public void swap(int i, int j)
{
// Swap the profits
double temp = profit[i];
profit[i] = profit[j];
profit[j] = temp;
// Swap the cities
String str = city[i];
city[i] = city[j];
city[j] = str;
}
}
You didn't provide your test/driver program, so I had to make a lot of assumptions.
Just write a method that loops through the two arrays and prints the values.
Your method to find the average profit looks fine.
You have a method to find the highest profit, but you need to display the city. I added a method to find the city with the highest profit.
//shows city with highest profit
String findHighestProfitCity()
{
double highest = profit[0];
String c = city[0];
for(int i = 1; i < profit.length; i++)
{
if ( profit [i] > highest ) {
highest = profit [i];
c = city[i];
}
}
return c;
}
This is a fairly straightforward method. Once you calculate the average, just loop through the city/profit arrays and display any cities that have a profit higher than the average.
The easiest way to do this with the data organized in two arrays would be to write a custom sort routine that sorts the profit array and makes a swap in the city array each time one is necessary in profit.
The test data you put in your city and profit arrays is way too big to display graphically. Your makeGraph() method tries to draws x asterisks for each value in profit. Even after cutting five zeroes off of each value, that still didn't fit on my screen, so I modifed that method to only draw x/10 asterisks for each profit
for(int j = 1; j <= x/10; j++)
s = s + "*";
Here's a test/driver program that you can use as a starting point.
package supermarkets;
public class SupermarketDriver {
/**
* #param args
*/
public static void main(String[] args) {
String[] cities = {"Miami", "Sunrise", "Hollywood",
"Tallahassee", "Jacksonville", "Orlando", "Gainesville", "Pensacola",
"Ocala", "Sebring"};
double[] profits = {102, 146, 170, 60, 216, 91, 80, 125, 20, 45};
Supermarkets sm = new Supermarkets(cities, profits);
System.out.println(sm.makeGraph());
System.out.println("Average profit: " + sm.average());
System.out.println();
System.out.println("Highest profit city: " + sm.findHighestProfitCity() + ", " + sm.findHighestProfit());
}
}