I'm having problems figuring out why returns for my minimum value in my array keep ending up as 0. I've checked several questions with the same problem but can't use those solutions because my array is being created in one method and my min/max values are calculated in another method.
Is there anyway I can keep my min/max value in a separate method and still get a non-zero answer for my min value? Also, there is more code in the processSalesReport method but I left it out because it was irrelevant. Thanks ahead of time!
import java.util.Arrays;
import java.util.Scanner;
public class CarSalesReport {
int sum;
int count = 0;
int[] num = new int[1500];
String ans = "";
Scanner userInput = new Scanner(System.in);
public CarSalesReport(Scanner input) {
String regex = "\\d+|done";
System.out.println("Type sales (type \"done\" when finished)");
do{
System.out.print("Sale Number " + (count + 1) + ": ");
ans = userInput.nextLine();
while(!ans.matches(regex)){
System.out.println("Please enter a positive number");
ans = userInput.nextLine();
}
if(!ans.equalsIgnoreCase("done")){
int ans1 = Integer.parseInt(ans);
num[count] = ans1;
count++;
}
}while(!ans.equalsIgnoreCase("done"));
}
public void processSalesReport(){
int max = num[0];
for(int a=0;a<num.length;a++){
if(max<num[a]){
max=num[a];
}
}
//This is where I'm having my problems.
int min = Integer.MAX_VALUE;
for(int a=1;a<num.length;a++){
if(min>num[a]){
min=num[a];
}
}
Arrays.sort(num);
System.out.println("\nMaximum sale: $" + max);
System.out.println("\nMinimum sale: $" + min);
}
}
It's because you've got 1500 entries in your array, which are all initialised to 0. You're iterating through all of them trying to find the minimum, instead of just iterating through the ones you've explicitly populated.
In the loop where you calculate the minimum, change
for (int a = 1; a < num.length; a++) {
to
for (int a = 0; a < count; a++) {
so that you only look at the entries that you've populated.
Related
I have an issue with my java program displaying every number it is adding, what can I do so that it only displays the total. I am guessing since I have "element" in the last part of the code it showing every single addition: Here is what I have written:
import java.util.Scanner;
public class SomeClass {
public static void main(String[]args){
int ans = 0;
int num;
Scanner keyboard = new Scanner(System.in);
System.out.println("How many integers do you have? (Max 20)");
int x= keyboard.nextInt();
int [] element = new int[x];
for(int subscript = 0; subscript < element.length; subscript++){
System.out.println("Enter element for subscript " + (subscript));
element[subscript] = keyboard.nextInt();
}
System.out.println("Here are all of those numbers");
for(int subscript = 0; subscript < element.length; subscript++){
num = element[subscript];
System.out.println(num);
}
for (int i = 0; i < element.length; i++){
ans += element[i];
System.out.println("The sum of these numbers is " + ans);
}
}
}
//previous lines of code
for (int i = 0; i < element.length; i++){
ans += element[i];
}
System.out.println("The sum of these numbers is " + ans);
//code follows
Because You print out the 'num' as many as length of element. You have to delete that line if your intention is to show only the summed ans which is result of sumation. If you wanna show inputs then its fine
Also
Take this sentence out of the for loop
System.out.println("The sum of these numbers is " + ans);
Everytime for loops working, that line works too. So make it works once after you add all the numbers with for loop.
I'm trying to get both, the largest number and the largest occurring number, from a user input. The problem with my code is it only returns the first value of the array.
public class CountMax {
public static void main(String [] args) {
//Create scanner object
Scanner input = new Scanner(System.in);
//Obtain user input
System.out.println("Enter numbers: ");
int num = input.nextInt();
int array[] = new int[num];
//loop through array
int max = array[0];
int count = 1;
for (int i = 0; i < array.length; i++) {
array[i] = num;
if(array[i] > max) {
max = array[i];
count = 1;
} else if(array[i] == max) {
count++;
}
}
//output results
System.out.println("The largest number is " + max);
System.out.println("The occurrence count of the largest number is " + count);
}}
I know this post is old, but Wyatt Lowery's solution is incorrect, just in case someones stumbles upon it from Google just like I did. You cannot count the number of max values in an array in the same loop like that until you have found the max value.
Example using Wyatt's class: 2 is obviously an incorrect answer.
Enter numbers:
1, 2, 3, 4, 5, 5, 7
The largest number is 7
The occurrence count of the largest number is 2
I would do:
int max = array[0];
int sum = 0;
for(int i = 1; i < array.length; i++) {
if(array[i] > max) max = array[i];
}
for(int i = 0; i < array.length; i++) {
if(array[i]==max) sum++;
}
One problem I noticed:
int num = input.nextInt();
When you do this, it is only going to take the first int (Meaning, only 1 number) As well when you are creating your array int array[] = new int[num], you are creating an array with the SIZE of num, and not actually creating an array with the VALUES of num. (Even though num is only a single number) To actually create an array of numbers, do something like this:
System.out.pritnln("Enter in numbers:");
String[] array = input.nextLine().split(", ");
An example input would be: "13, 12, 14, 14". Then the contents of the array would be those terms (And would remove spaces & commas). Your program should look something like this when finished:
public class CountMax {
public static void main(String [] args) {
//Create scanner object
Scanner input = new Scanner(System.in);
//Obtain user input
System.out.println("Enter numbers: ");
String[] array = input.nextLine().split(", ");
//Loop through array
int max = Integer.parseInt(array[0]);
int count = 0;
for (int i = 0; i < array.length; i++) {
if(Integer.parseInt(array[i]) > max) {
max = Integer.parseInt(array[i]);
} else if(Integer.parseInt(array[i]) == max) {
count++;
}
}
//Output
System.out.println("The largest number is " + max);
System.out.println("The occurrence count of the largest number is " + count);
}
}
Hope this helped :-)
Think more carefully about each step you need to take.
Do you know how many numbers will be entered by the user?
Right now you are only taking in one number because you are not looping on the input
int num = input.nextInt();
int array[] = new int[num];
Here, you are creating an array the size of whatever number the user entered. This is a correct approach, more typical of C, if the user will tell you "I will enter 10 numbers" and then enters the 10 numbers. This is convenient because you will know to loop 10 times, and you will need to count a maximum of 10 different numbers.
If we don't know how many numbers will be entered you will need to loop until EOF.. something like
while(input.hasNext()) {
int currentInt = input.next();
...
}
Now you have to consider how you will be counting these items.
I hope this gives you some things to think about towards your solution..
What I'm trying to do is create an array based on values given by the user. The user has to give the length of the array plus the max and min values. I've managed to get the program to the point where it does output the correct amount of values (the correct length), but it just keeps outputting the exact same number (which is the max and min added). Based on research I did I tried converting them to a string so that wouldn't happen, but it still isn't working correctly. I've tried a couple of different methods including: Integer.toString, String.valueOf, and creating a whole new string. Any help would be greatly appreciated. Here's the code so far:
public static void main(String[] args) {
//Create a Scanner object
Scanner input = new Scanner(System.in);
//Ask the user to enter the length of the array
System.out.println("Please enter the length of the array:");
int arraylength = input.nextInt();
//Ask the user to enter a max value
System.out.println("Please enter the max value:");
int max = input.nextInt();
//Ask the user to input the minimum value
System.out.println("Please enter the min value:");
int min = input.nextInt();
//Initialize the array based on the user's input
double [] userArray = new double[arraylength];
/**
*The program comes up with random numbers based on the length
*entered by the user. The numbers are limited to being between
*the minimum and maximum value.
*/
for (int i = min; i < userArray.length; i++) {
userArray[i] = Math.random() * max;
}
//This code is supposed to sort the array and print out all of the numbers in order,
//with minimum in the beginning and max in the end.
for (int i = 0; i < userArray.length; i++) {
selectionSort(userArray);
Integer.toString(min);
Integer.toString(max);
System.out.println(min + userArray[i] + max);
}
//This code uses the method average to find the average
average(userArray);
//Close Scanner
input.close();
}
public static double average(double[] data) {
double sum = 0;
for (int i = 0; i < data.length; i++) {
sum = sum + data[i];
}
double average = sum / data.length;
return average;
}
public static void selectionSort(double[] list) {
for (int i = 0; i < list.length - 1; i++) {
//Find the minimum in the list[i...list.length-1]
double currentMin = list[i];
int currentMinIndex = i;
for (int j = i + 1; j < list.length; j++) {
if (currentMin > list[j]) {
currentMin = list[j];
currentMinIndex = j;
}
}
//Swap list[i] with list[currentMinIndex] if necessary
if (currentMinIndex != i) {
list[currentMinIndex] = list[i];
list[i] = currentMin;
}
}
}
}
Now, after I added that bit with the average calculation, the program did work once, though it did not compute the average (so it just created an array with min and max at the ends, sorted). It appears to be a fluke, because this is the exact same code and it hasn't done that since. Though maybe the average code somehow affected the rest?
If I understood you problem correctly, you need to change this line
System.out.println(min + userArray[i] + max);
to this:
System.out.println(min.toString() + " " + userArray[i].toString() + " " + max.toString());
My guess is, that it is java you are using. That tag would be helpful, too.
Edit:
You only need to sort your array once, and these do nothing: Integer.toString(min);
So the print routine could look like this:
selectionSort(userArray);
for (int i = 0; i < userArray.length; i++) {
System.out.println(min.toString() + " " + userArray[i].toString() + " " + max.toString());
}
The code below is what I have wrote for my assignment for class.
I have not learned from the instructor yet about the arrays, and
data. I have understood how to use the arrays, but not quite sure
about the data yet.
I have marked where I need help for the code below.
Although I have managed to write it, still not sure if it is optimal.
Could someone help me to better it perhaps?
*I asked previously about finding the mode, and people told me to do it with the
map implementation, I tried to do it, but my brain won't work for it.. any suggestions?
=================================================================================
import java.util.Scanner;
import java.util.Arrays;
public class CodeVer2 {
public static void main(String[] args)
{
Double num1, num2, num3, num4, num5, sum, avg;
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter the first number:");
num1 = keyboard.nextDouble();
System.out.println("Enter the seond number:");
num2 = keyboard.nextDouble();
System.out.println("Enter the third number:");
num3 = keyboard.nextDouble();
System.out.println("Enter the fourth number:");
num4 = keyboard.nextDouble();
System.out.println("Enter the fifth number:");
num5 = keyboard.nextDouble();
keyboard.close();
double[] num = new double[5]; // array named num is declared with 5 variables
num[0] = num1;
num[1] = num2;
num[2] = num3;
num[3] = num4;
num[4] = num5;
Arrays.sort(num);
double[] data = {num1, num2, num3, num4, num5}; // I need help from here,
int mode = 0;
int[] index = new int[999];
int maximum = Integer.MIN_VALUE;
for (int i = 0; i < data.length; i++){
index[(int) data[i]]++;
}
for (int i = 0; i < index.length; i++){
if(maximum < index[i]){
maximum = index[i];
mode = i;
}
} // to here.
sum = num[0] + num[1] + num[2] + num[3] + num[4];
avg = sum/5;
System.out.println(" ");
System.out.println("Sum:" + sum);
System.out.println("Avg:" + avg);
System.out.println("Max:" + num[4]);
System.out.println("Min:" + num[0]);
System.out.println("Median:" + num[2]);
System.out.println("Mode:" + mode);
}
}
So all double[] does is set up an array that can contain 0 or more numbers. Think of it like a sheet of paper with a row of boxes on it. You can't add more boxes or take them away but you can write a different number in each box.
double[] data = {num1, num2, num3, num4, num5}; // I need help from here,
This creates a row of boxes, and writes the numbers in the { } into the row. It automatically creates the row to be the right size to hold the things in the brackets.
int mode = 0;
int[] index = new int[999];
int maximum = Integer.MIN_VALUE;
This creates a new list of boxes, these ones can each hold an integer and there are 999 of them.
for (int i = 0; i < data.length; i++){
index[(int) data[i]]++;
}
This loops through your data. data[i] says "use the value in the box numbered i, counting from the start of the boxes with the first box being 0".
It converts that double value to an integer and then looks up the box corresponding to that integer. It adds one to the value at that position. Note that there is a flaw in the algorithm here, if someone puts in a number over 999 then you won't have enough boxes.
for (int i = 0; i < index.length; i++){
if(maximum < index[i]){
maximum = index[i];
mode = i;
}
}
Now this loops through every box in the index array. Since earlier values are over-ridden and since you never actually calculate the maximum it actually just gives you the value in box 999 of the array and sets mode to 999. That doesn't sound very useful...
first of all I rewrote your code to make it easier to read.
What is missing is: what does this "mode" mean. I couldn't derive it from your code.
The code below is not perfect. A lot of error handling and boundary checking is missing. I leave that as an exercise for you.
So, try to understand what my code does. Think about the meaning of "mode" and how to calculate it.
import java.util.Scanner;
import java.util.Arrays;
public class CodeVer2 {
static final String CARDNAME[] = { "first", "second", "third", "fourth", "fifth" };
static final int NUM_ITEMS = 5;
public static void main(String[] args)
{
double num[], sum, avg, max, min;
double mode = 0.0; // don't know what this is
int i;
num = new double[NUM_ITEMS];
sum = 0;
max = Double.NEGATIVE_INFINITY;
min = Double.POSITIVE_INFINITY;
Scanner keyboard = new Scanner(System.in);
for (i = 0; i < NUM_ITEMS; ++i) {
System.out.println("Enter the " + CARDNAME[i] + " number:");
num[i] = keyboard.nextDouble();
sum += num[i];
if (max < num[i]) max = num[i];
if (min > num[i]) min = num[i];
}
avg = sum / NUM_ITEMS;
Arrays.sort(num);
keyboard.close();
System.out.println(" ");
System.out.println("Sum:" + sum);
System.out.println("Avg:" + avg);
System.out.println("Max:" + max);
System.out.println("Min:" + min);
System.out.println("Median:" + num[NUM_ITEMS/2]);
System.out.println("Mode:" + mode);
}
}
I have two files that I am using for my Array median code. The first file( ArrayMedian.java) is used to collect and then calculate the median, the second file is the tester file ( ArrayMedianTest.java)
I was supplied with some source code and needed to modify it accept a set range for each number in the dataset. I got that part done and the random range displays, but now when I get to he array it no longer calculates, I really can't put my finger on what is going wrong.
Another thing I am trying to do is in the ArrayMedian, is put a while loop in there to make it terminate if a '0' is input for the dataset, but it does not seem to want to work in that file, could it be due to no main in the file?
package bonus2.u06.exercise.ex3;
import java.util.Scanner;
public class ArrayMedian {
private int[] arr; // just declare array
Scanner keyboard; // shared field
// initialize keyboard and array
public void init() {
keyboard = new Scanner( System.in );
System.out.print("Enter the dataset size: ");
int size = keyboard.nextInt(); // must be odd number
arr = new int[ size ]; // instantiate
}
// Randomize the array
public void getRange() {
//System.out.println("\nYou entered: ");
System.out.print("Enter a Range: ");
int range = keyboard.nextInt();
System.out.print("array: \n");
for(int i = 0; i < arr.length; i++){
int myRnd = (int)( range * Math.random() );
System.out.print(" " + myRnd + " ");
}
}
// find the median of array
public int calcMedian() {
int half_length = arr.length/2;
for (int i = 0; i < arr.length; i++) {
int count = 0;
for (int j = 0; j < arr.length; j++) {
if (arr[i] > arr[j])
count++;
}
if (count == half_length) {
//<========= terminate this method
return arr[i];
}
}
return 0;
}
}
ArrayMedianTest:
package bonus2.u06.exercise.ex3;
public class ArrayMedianTest {
public static void main(String args[]) {
// instantiate
ArrayMedian obj = new ArrayMedian();
// execute all methods
obj.init();
obj.getRange();
int median = obj.calcMedian();
System.out.println("\nmedian : " + median);
System.out.println("\n--- done ---");
}
}
Turn out, your algorithm works perfectly fine, except in the getRange() method, you forgot to set the values of the array, so the array is an array of zeros. Here is how it should look:
public void getRange() {
//System.out.println("\nYou entered: ");
System.out.print("Enter a Range: ");
int range = keyboard.nextInt();
System.out.print("array: \n");
for(int i = 0; i < arr.length; i++){
int myRnd = (int)( range * Math.random() );
System.out.print(" " + myRnd + " ");
arr[i] = myRnd; // <-- You missed this line right here!
}
}
Also, as a recomendation, if you want to put code in stackoverflow, it has to have a spacing of four at the begining of the line plus any indenting you might use. Good luck programming!