Displaying two arrays in tester class - java

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());
}
}

Related

Display Min/Max array

The final output will show who has the highest grade and who has the lowest grade.
I'm lost on how to call the lowest name/grade to the final output.
In the code I have some comments on where I'm stuck with the "currentMinIndex", the "currentMaxIndex" works just fine and will show it to the final output. I tried to mirror it but it isn't going how I expected. Not sure if something with "(int k = 1; k>= m; k++)" is incorrect.
import java.util.*;
public class MyArrayEX {
// Sort grades lowest on top
public static int[] reverseInt(int[] array) {
int[] input = new int[array.length];
for (int i = 0, j = input.length - 1; i < array.length; i++, j--) {
input[j] = array[i];
}
return input;
}
public static void main(String[] args) {
// Scanners
Scanner input = new Scanner(System.in);
Scanner keyboard = new Scanner(System.in);
// Input amount
System.out.print("\nEnter number of students: ");
int numOfStu = input.nextInt(); // Number of Students
int[] grades = new int[numOfStu];
String[] names = new String[numOfStu];
// Start loop, amount is based off of "numOfStu"
for (int i = 0; i < numOfStu; i++) {
System.out.print("\rEnter student first name: ");
String name = keyboard.next();
System.out.print("Enter the students grade: ");
int grade = input.nextInt();
// Assigning i
names[i] = name;
grades[i] = grade;
//System.out.println("");
}
// This is the area that sorts it from least to greatest
// i is the indexed value of the last number in array
for (int i = grades.length - 1; i > 0; i--) {
// Resets both to 0 to start at the beginning of the array
int currentMax = grades[0];
int currentMaxIndex = 0;
// i is back-limit that gets chopped off by one each time
for (int k = 1; k <= i; k++) {
if (currentMax < grades[k]) {
currentMax = grades[k];
currentMaxIndex = k;
}
}
// This is where im lost on how to call the min value
// Trying to mirror the one above but using it
// to show the minimum grade along with the name
for (int m = grades.length - 1; i > 0; i--) {
int currentMin = grades[0];
int currentMinIndex = 0;
// Min grades
for (int k = 1; k >= m; k++) {
if (currentMin < grades[m]) {
currentMin = grades[m];
currentMinIndex = m;
}
}
// After largest number is found, assign that number to i
// Im trying to have the final output show the min/max grade with who has it
// Would the MinIndex be assigned to a different variable?
grades[currentMaxIndex] = grades[i];
grades[currentMinIndex] = grades[m];
grades[i] = currentMax;
grades[m] = currentMin;
String highName = names[currentMaxIndex];
String lowName = names[currentMinIndex];
names[currentMaxIndex] = names[i];
names[currentMinIndex] = names[m];
names[i] = highName;
names[m] = lowName;
// This shows the name and grade for the highest number
System.out.print("\rThe highest grade is " + highName + " with a " + currentMax);
// Unsure how to call this.
System.out.println("\r and the Lowest grade is " + lowName + " with a " + currentMin);
}
}
input.close();
keyboard.close();
}
}
Your code has multiple problems. First is with the 2 scanners that you are using for same System.in input stream and second you are using nested loops to find the min/max values which is totally unnecessary. Since the question is about finding the min/max so I will focus on that part only and for the scanner I would say remove the keyboard scanner and use only input scanner. Anyways, use the following code block to find the maximum and minimum grades with names:
int currentMaxIndex = 0;
int currentMinIndex = 0;
// Get min max
for (int i = 1; i<grades.length; i++) {
if (grades[currentMaxIndex]<grades[i]) {
currentMaxIndex=i;
}
if (grades[currentMinIndex]>grades[i]) {
currentMinIndex=i;
}
}
String highName = names[currentMaxIndex];
String lowName = names[currentMinIndex];
int currentMax = grades[currentMaxIndex];
int currentMin = grades[currentMinIndex];
System.out.print("\rThe highest grade is " + highName + " with a " + currentMax);
System.out.println("\r and the Lowest grade is " + lowName + " with a " + currentMin);
The approach is quite simple. We first aasume that the first element in the grades array is min and max then we loop to the remaining elements from 1 to grades.length and compare the index min/max to the current index element values and accordingly change our min/max indices. If the current index value is greater than currentMaxIndex then we copy it to currentMaxIndex and same but opposite for currentMinIndex. So in the end we will have the highest and lowest value indices of grades array. The complete code is here https://ideone.com/Qjf48p

How can I display the largest amount in my 2D array?

import java.util.Arrays;
import java.util.ArrayList;
import java.util.Random;
public class labb8 {
public static void main(String[] args) {
Random rnd = new Random();
int[][] sales = new int[5][7];
int[] total = new int[sales.length];
ArrayList<String> unpopularSoftware = new ArrayList<String>();
String[] locations = {"Houston", "Dallas", "Hunts", "San Ant", "Austin"};
System.out.println("Location\t| Software Sales\t\t| Total Sales");
System.out.println("--------------------------------------------------");
for (int i = 0; i < sales.length; i++) {
for (int j = 0; j < sales[i].length; j++) {
sales[i][j] = rnd.nextInt(25);
total[i] += sales[i][j];
}
System.out.print(locations[i] + "\t\t|");
System.out.print(" " + Arrays.toString(sales[i]));
System.out.println("\t| " + total[i]);
}
int unpopularModelCounter;
for (int j = 0; j < sales[0].length; j++) {
unpopularModelCounter = 0;
for (int i = 0; i < sales.length; i++) {
if (sales[i][j] != 0) {
unpopularModelCounter++;
}
}
if (unpopularModelCounter <= 3) {
unpopularSoftware.add("Software " + (j + 1));
}
}
System.out.println("Unpopular Software: " + unpopularSoftware);
System.out.println("Location with most sold licenses: ");
}
}
Above is the code and it gives me the results I'm looking for; however, I'd like to know some methods on how can I print out the name of the location that has the most sold software? What I've tried is putting System.out.println(total[i]); under System.out.println("\t| " + total[i]); but that just displayed all the totals, which is what I figured would happen. I've also tried putting System.out.println(total[i]); where the other output lines are at the bottom(which is where I want it), but the code can't find [i], which made me believe that I might have to create some methods; so, again, I'm asking for some course of advice on how to print out the name of the city with the largest amount sold in terms of my code.
If you want the name of the city the the highest total, you need to look through the total array for the largest total and, while doing that, keep track of both the largest total you've seen so far and the index at which you saw that largest total.
Something like this should do the job nicely:
// Our initial guess is that `total[0]` is the maximum sales total.
int maxSales = total[0];
int maxI = 0;
for (int i = 1; i < total.length; ++i) {
if (totals[i] > maxSales) {
maxSales = total[i];
maxI = i;
}
}
System.out.println(locations[maxI] + " has the most sales: " + maxSales);
Maybe try adding this to the end of the code.
int max = 0; // stores the maximum value
for (int i = 0; i < total.length; i++) {
max = Math.max(max, total[i]);
}
System.out.println(max);
This should print the greatest value of the total array. I like your code!

2D array column average java

I have 2 arrays, String[][] names and int[][] grades, to store the names and grades of a class I am trying to print as a table in a much longer code. I was able to calculate the average of each row with a method I called in the main. I'm having a hard time figuring out how to do the average of each column though. Any suggestions would be appreciated. For the row averages I wrote a method:
//determine average for each student
public double rowAverage(int[] rowOfGrades) {
int total = 0;
//sum grades for each student
for(int grade : rowOfGrades){
total += grade;
}
//return average of student grades
return (double) total/rowOfGrades.length;
}//end getAverage
and then printed it in my main with
//creates rows and columns of text for array names and grades
for(int student=0; student<names.length; student++) {
System.out.printf("%s",names[student]); //student name
for(int test : grades[student]) {
System.out.printf("\t%7d",test); //test grades
}
//call method getAverage to calculate students grade average
//pass row of grades as the argument to getAverage
double average = rowAverage(grades[student]);
System.out.printf("%12.2f", average);
}
For each test you have to iterate over the students:
for (int test = 0; test < grades.length; test++) {
int total = 0;
for(int student=0; student<names.length; student++) {
total += grades[student][test]
}
double avgForTest = (double) total/names.length;
}
Make a new array w/ the values for the column you are interested in; rowAverage will compute the average for that array (thus that column). Repeat for each column.
to access each column of a row you will have to access its length field e.g. names[student].length
example
int[][] towers = new int[8][8];
int myNumber=25;
for(int row=0;row<towers.length;++row)
{
for(int column=0;column<towers[row].length;++column)
{
if(myNumber==towers[row][column])
{
System.out.println("I found you");
column=towers[row].length;
row=towers.length;
}
}
}
You can try like
for (int i = 0; i < 2; i++) {
int rowSum = 0;
int colSum = 0;
double rowAvg = 0.0;
double colAvg = 0.0;
for (int j = 0; j < 2; j++) {
rowSum += arr[i][j];
colSum += arr[j][i];
}
rowAvg = rowSum / 2.0;
colAvg = colSum / 2.0;
System.out.println(i + " row average: " + rowAvg);
System.out.println(i + " column average: " + colAvg);
}

How do i find max and min of an nested ArrayList?

Let's say i have N ArrayLists and inside them, there are M other ArrayLists, so i'm trying to find the min and max of each of these M ArrayLists, what's the best way to do that?
ArrayList<String> myname = new ArrayList<String>(n);
ArrayList<Integer> myscore = new ArrayList<Integer>(m);
for (int i = 0; i < n; i++) {
System.out.println("enter name of contestant");
myname.add(input.next());
for (int j = 0; j < m; j++) {
System.out.println("enter score");
myscore.add(input.nextInt());
}
You can use IntSummaryStatistics class:
IntSummaryStatistics istats = IntStream.of(1,22,33,44,55).
collect(IntSummaryStatistics::new, IntSummaryStatistics::accept,
IntSummaryStatistics::combine);
System.out.println("Max: "+istats.getMax()+", Min: "+istats.getMin());
// Max: 55, Min: 1
Your question is not that much explanatory. Lets say that you want to add the names of some student and you also want to save the corresponding marks obtained by each student. So you will need three ArrayList reference variable. First one is for storing the names, second one is for storing the marks obtained by the student, and the third one is for storing the ArrayList of marks obtained by a single student. Here goes the code
package exmaple;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Scanner;
public class Finder {
public static void main(String[] args) {
Scanner userInput = new Scanner(System.in);
int n = userInput.nextInt();
int m = userInput.nextInt();
ArrayList<String> names = new ArrayList<String>(n);
ArrayList<Integer> numbers;
ArrayList<ArrayList<Integer>> holderOfMarksArayList = new ArrayList<ArrayList<Integer>>();
for(int i = 0; i<n; i++) {
System.out.println("Enter name of contentant.");
String name = userInput.next();
names.add(name);
numbers = new ArrayList<Integer>(m);
for(int j = 0; j<m; j++) {
System.out.println("Enter score.");
numbers.add(userInput.nextInt());
}
holderOfMarksArayList.add(numbers);
}
int counter = 0;
for(String name : names) {
numbers = holderOfMarksArayList.get(counter);
Collections.sort(numbers);
int maxScore = numbers.get(numbers.size() - 1);
int minScore = numbers.get(0);
System.out.println(name +", Max Score = " + maxScore + " Min Score = " + minScore);
counter++;
}
userInput.close();
}
}
If you try with the following input
AAA = 20, 80, 10
XXX = 66, 98, 96
YYY = 65, 12, 76
You will get the following output
AAA, Max Score = 80 Min Score = 10
XXX, Max Score = 98 Min Score = 66
YYY, Max Score = 76 Min Score = 12
You can use Collections.max(arrayList). Just to illustrate how it works.
public static void main(String[] args)
{
ArrayList<ArrayList<Integer>> n = new ArrayList<>();
ArrayList<Integer> m0 = new ArrayList<>();
ArrayList<Integer> m1 = new ArrayList<>();
m0.add(100);
m0.add(200);
m0.add(300);
m0.add(400);
n.add(m0);
m1.add(10);
m1.add(20);
m1.add(30);
m1.add(40);
n.add(m1);
System.out.println(n);
System.out.println(Collections.max(n.get(0)));
System.out.println(Collections.min(n.get(0)));
System.out.println(Collections.max(n.get(1)));
System.out.println(Collections.min(n.get(1)));
}
RUN
[[100, 200, 300, 400], [10, 20, 30, 40]]
400
100
40
10
For your case, you can loop through your n arraylists to get the min and max of each of them.
If you want to find out the winner you should sum the marks obtained by each winner and compare it with a temp variable. if the sum is greater then the temp then assign the sum to the temp. the last value assigned in the temp will be highest mark obtained. After the first for loop the code will be like that.
String winnerName = "";
int temp = 0;
int counter = 0;
for(String name : names) {
numbers = holderOfMarksArayList.get(counter);
int sum = 0;
for( int number : numbers ) {
sum += number;
}
if( sum > temp ) {
temp = sum;
winnerName = name;
}
Collections.sort(numbers);
int maxScore = numbers.get(numbers.size() - 1);
int minScore = numbers.get(0);
System.out.println(name +", Max Score = " + maxScore + " Min Score = " + minScore +" Sum " + sum);
counter++;
}
System.out.println("Winner " + winnerName + " Total "+ temp);

Average Class not working

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().

Categories

Resources