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

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!

Related

Array with bubble sort and odd/even list - Anyone knows how to remove duplicate element in my even list?

Regardless of the programming language you use. You will undoubtedly encounter data while dealing with arrays, particularly duplicates, that you will want to get rid of.
This is my Output
I already inputted the correct syntax of even list array is there something that I missed?
Anyone knows how to remove duplicate element in my even list?
Here's my code:
import java.util.*;
import java.util.Iterator;
public class ArrayBubbleSortwithOddandEven {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int size, temp;
System.out.print("Size of the list: ");
size = scanner.nextInt();
int number[] = new int[size];
int oddarray[] = new int[size];
int evenarray[] = new int[size];
int odd = 0;
int even = evenarray.length - 1;
for (int i = 0; i < number.length; i++) {
System.out.print("Input: ");
number[i] = scanner.nextInt();
}
for (int i = 0; i < size; i++) {
for (int swap = 1; swap < (size - i); swap++) {
if (number[swap - 1] > number[swap]) {
temp = number[swap - 1];
number[swap - 1] = number[swap];
number[swap] = temp;
}
}
}
for (int i = 0; i < number.length; i++) {
if (number[i] % 2 != 0) {
oddarray[odd++] = number[i];
} else {
evenarray[even--] = number[i];
}
}
for (int i = 0; i < number.length; i++) {
evenarray[even] = evenarray[i];
}
for (int i = 0; i < number.length; i++) {
oddarray[odd] = oddarray[i];
}
for (int i = 0; i < size; i++) { //Bubble sort
for (int swap = 1; swap < (size - i); swap++) {
if (evenarray[swap - 1] > evenarray[swap]) {
temp = evenarray[swap - 1];
evenarray[swap - 1] = evenarray[swap];
evenarray[swap] = temp;
}
}
}
System.out.println("Odd List:"); //Print Odd list
for (odd = 0; odd < oddarray.length; odd++) {
System.out.println("List " + odd + ": " + (oddarray[odd]));
}
System.out.println("Even List:"); //Print Even list
for (even = 0; even < evenarray.length; even++) {
System.out.println("List " + even + ": " + (evenarray[even]));
}
}
}
you can use a Set\HashMap to remember which number you already discover during your iteration. GOOD LUCK !
You can read about Data Structures - just google it :).
here a few questions that might help you understand.
Data Structures for hashMap, List and Set
Why key in HashMap can't be duplicated
how to find duplicate item position from set in java

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

Not sure how to develop two methods for this code

I need the first method for generating a random number should receive the beginning and ending value of the range within its parameter list. It should send back the random number through the method name. And the second method to display the array which I have but apparently the code is not broken down into two methods and I don't understand how to accomplish this. I am lost after working on this for so long.
Here is my UPDATED code but still receiving 4 errors:
import java.util.Scanner;
import java.util.Random;
public final class {
public static Random generator = new Random();
public int createNum(int[] randomNumbers, int SIZE, int n, int i) {
int x;
SIZE = 20;
randomNumbers = new int[SIZE];
Random generator = new Random();
for (i = 0; i < SIZE; i++) {
n = generator.nextInt(10) + 1;
randomNumbers[i] = n;
}
return n;
}
public void print(int i, int randomNumbers, int SIZE){
SIZE = 20;
randomNumbers = new int[SIZE];
for (i = 0; i < SIZE; i++) {
System.out.println("Number " + i + " : " + randomNumbers[i]);
}
}
public static void main(String[] args){
do{
Scanner inputReader = new Scanner(System.in);
System.out.print("Do you wish to restart the program, Enter 1 for YES, 2 for NO: ");
x = inputReader.nextInt();
} while (x == 1);
}
}
First thing's first, don't put everything in main if the task is to decompose your solution. What you need is a class that exercises the logic of your requirements or at least two additional methods that perform the work independently.
This code:
for (int i = 0; i < randomNumbers.length; i++) {
int n = generator.nextInt(10) + 1;
randomNumbers[i] = n;
}
for (int i = 0; i < randomNumbers.length; i++) {
System.out.println("Number " + i + " : " + randomNumbers[i]);
}
represents two distinct tasks. You can tell because they are not dependent on each other.
This code:
for (int i = 0; i < randomNumbers.length; i++) {
int n = generator.nextInt(10) + 1;
randomNumbers[i] = n;
}
generates and places the numbers.
This code:
for (int i = 0; i < randomNumbers.length; i++) {
System.out.println("Number " + i + " : " + randomNumbers[i]);
}
prints them.
Since it seems beneficial for you to figure this out on your own; what's needed now? hint: read the first part again

How to list individual students grades...?

Using multi-dimensional arrays is a first for me, so my understanding of some of the aspects that come with these arrays are a bit...vague. Now for a quick review of what this program will be used for once completed...
It collects the inputted students names and four corresponding test scores. You can find the average of the school with it and now I'm attempting to find average of each individual student.
public class StudentGradesView extends FrameView {
int [][] aryStudent = new int [15][4]; // [15] being max students [4] being # of test scores
String[] studentNames = new String[15];
int numOfStudents = 0; //student names start from 0...
int marks = 0;
int test1;
int test2;
int test3;
int test4;
public StudentGradesView(SingleFrameApplication app) {
//unimportant...for GUI
}
private void addButtonActionPerformed(java.awt.event.ActionEvent evt) {
//this is fine...just collects the names and test scores and ists them in studentListField...
aryStudent[numOfStudents][0] = Integer.parseInt(test1Field.getText());
aryStudent[numOfStudents][1] = Integer.parseInt(test2Field.getText());
aryStudent[numOfStudents][2] = Integer.parseInt(test3Field.getText());
aryStudent[numOfStudents][3] = Integer.parseInt(test4Field.getText());
StringBuilder sb = new StringBuilder();
for (int x=0; x <= numOfStudents && x<15; x++) {
sb.append(firstNameField.getText() + " " + lastNameField.getText());
for (int y=0; y < 4; y++) {
sb.append(" " + aryStudent[x][y]);
}
sb.append("\n");
}
studentListField.setText(sb.toString());
numOfStudents ++;
}
private void classAverageButtonActionPerformed(java.awt.event.ActionEvent evt) {
//finds school average....its fine
for(int x = 0; x < numOfStudents && x<15; x++) {
averageField.setText("The class average is " + (aryStudent[x][0] + aryStudent[x][1] + aryStudent[x][2] + aryStudent[x][3])/4 + "%");
}
}
private void studentAverageButtonActionPerformed(java.awt.event.ActionEvent evt) {
But then! This...I thought this would list the students averages individually, but it only inputs one student at a time, which is a problem...All it needs to do is list similar to this...
John Smith 78
Jane Doe 80
etc etc
for (int i = 0; i < numOfStudents; i++) {
for (int y = 0; y < marks; y++) {
averageField.setText("Student" + (aryStudent[y][0] + aryStudent[y][1] + aryStudent[y][2] + aryStudent[y][3])/4);
}
}
marks++;
}
what is exactly the variable marks in the last piece of code? it is outside the loop so it does not actually do anything. What I expect your code to do if for instance there are 4 students and marks is 3 would be the following
(i=0 y=0), StudentA
(i=0 y=1), StudentB
(i=0 y=2), StudentC
(i=1 y=0), StudentA <AVG>
(i=1 y=1), StudentB <AVG>
(i=1 y=2), StudentC <AVG>
(i=2 y=0), StudentA <AVG>
(i=2 y=1), StudentB <AVG>
(i=2 y=2), StudentC <AVG>
....
Try to print your results in text mode first (without any GUI). When it will work there you can move to GUI.
Your indices does not appear to be correct. You're using y, which is the mark index as the student index, and i is unused. Also, the way you did it, you don't need 2 loops.
This problem might've been avoided if you named i s for student and y m for mark.
Also, by using setText, you're replacing the text, not adding to it. Assuming you're using a JTextArea, you should use append instead.
It should look like:
averageField.setText(""); // clear
for (int s = 0; s < numOfStudents; s++)
averageField.append(studentNames[s] + " - " + (aryStudent[s][0] +
aryStudent[s][1] + aryStudent[s][2] + aryStudent[s][3])/4 + "\n");
A more generic way:
averageField.setText(""); // clear
for (int s = 0; s < numOfStudents; s++)
{
int average = 0;
for (int m = 0; m < marks; m++)
average += aryStudent[s][m];
average /= 4;
averageField.append(studentNames[s] + " - " + average + "\n");
}
Note that you're class average also appears to be incorrect. It currently only shows the last student's average (setText also replaces as you go).
Something like this should work:
int average = 0;
for (int s = 0; s < numOfStudents; s++)
for (int m = 0; m < marks; m++)
average += aryStudent[s][m];
average /= numOfStudents * marks;
averageField.setText("The class average is " + average + "%");
Also, wouldn't (or shouldn't) numOfStudents be limited to 15, why are you checking for both values?

Displaying two arrays in tester class

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

Categories

Resources