Hi in my program I want to display the average number, largest number, lowest number, and the mode in the array. So far only my average works and my methods for min and max both = the first number I enter. For example if I say I want to enter 3 numbers and I put 12, 15,and 6. The min and max will both output 12 since it's the first number entered and that's wrong so please help. Here's my code.
int amount;
System.out.println(" Enter the amount of numbers you would like to enter: ");
amount = scan.nextInt();
int [] arr = new int [amount];
int outcome = 1;
for (int i = 0; i < arr.length; i++){
System.out.println("Enter a number 1 through 50");
outcome = scan.nextInt();
arr [i] = outcome;
}
System.out.println(" ");
System.out.println( " The average is" );
System.out.println(average(arr));
System.out.println(" ");
System.out.println( " The lowest value in the array is " );
System.out.println(min(arr));
System.out.println(" ");
System.out.println( " The largest value in the array is " );
System.out.println(max(arr));
System.out.println(" ");
}
public static double average ( int [] arr) {
double sum = 0;
int value = arr.length;
for ( int i = 0; i < arr.length; i++){
sum += arr [i];
}
sum = sum / value;
return sum;
}
public static int min (int [] arr) {
int shortest = 0;
int smallest = 100;
int length = arr.length;
for ( int i = 0; i < arr.length; i ++ ) {
if ( length < smallest)
shortest += arr[i];
smallest = arr.length;
}
return shortest;
}
public static int max (int [] arr) {
int largest = 0;
int biggest = 0;
int length = arr.length;
for ( int i = 0; i < arr.length; i ++ ) {
if ( length > largest)
biggest += arr[i];
largest = arr.length;
}
return biggest;
}
}
This would be pretty straightforward. The reason both your min and max methods return 12 is because you set both largest and smallest to arr.length and thus immediately stop the for-loop after only one run. Also, there are far easier implementations for this kind of problem. Try doing something along these lines:
public int getMax(int[] arr)
{
int max = arr[0]; //To have a baseline
for(int i = 1; i < arr.length; i++)
{
if(arr[i] > max)
{
max = arr[i];
}
}
return max;
}
public int getMin(int[] arr)
{
int min = arr[0]; //To have a baseline
for(int i = 1; i < arr.length; i++)
{
if(arr[i] < min)
{
min = arr[i];
}
}
return min;
}
This is both far more readable and easier to execute. Just ask if you have any questions :-)
Related
I want to be able to display the output as three lines of text at the end but I'm getting a really weird output. So for example
"The average is z"
"Min Value: x"
"Max Value: y"
But I am getting this:
Please enter the size of the array:
3
Please enter array elements:
10
The average is 3.
Min Value: 0
Please enter array elements:
20
The average is 10.
Max Value: 20
Min Value: 0
Please enter array elements:
30
The average is 20.
Max Value: 20
Max Value: 30
package arrays;
import java.util.Scanner;
public class AssignmentArrays {
public static void main (String[] args) {
Scanner inputs = new Scanner(System.in);
System.out.println("Please enter the size of the array: ");
int size = inputs.nextInt();
int[] Array = new int[size];
for (int i = 0; i < size;) {
System.out.println("Please enter array elements: ");
int value = inputs.nextInt();
if (value >=100 || value <=0) {
System.out.println("Only values greater than 0 and less than 100 can be accepted.");
}
else {
Array[i] = value;
i++;
average(Array);
getMaxValue(Array);
getMinValue(Array);
}
}
}
public static int average(int[] Array)
{
int sum = 0;
int average;
for (int i = 0; i < Array.length; i++)
sum = sum+Array[i];
{
average=sum/Array.length;
System.out.println("The average is " +average +".");
return average;
}
}
public static int getMaxValue(int[] Array) {
int maxValue = Array[0];
for (int i = 1; i < Array.length; i++){
if (Array[i] > maxValue){
maxValue = Array[i];
System.out.println("Max Value: " + maxValue);
}
}
return maxValue;
}
public static int getMinValue(int[] Array) {
int minValue = Array[0];
for (int i = 1; i < Array.length; i++){
if (Array[i] < minValue) {
minValue = Array[i];
System.out.println("Min Value: " + minValue);
}
}
return minValue;
}
}
Thank you for all your help! I have finished my assignment.
example output: https://i.stack.imgur.com/Doy2d.png :)
package arrays;
import java.util.Scanner;
public class Array_1 {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner inputs = new Scanner(System.in);
System.out.println("Please enter the size of the array: ");
int size = inputs.nextInt();
int[] Array = new int[size];
for (int i = 0; i < size;) {
System.out.println("Please enter array elements: ");
int value = inputs.nextInt();
if (value >=100 || value <=0) {
System.out.println("Only values greater than 0 and less than 100 can be accepted.");
}
else {
Array[i] = value;
i++;
}
}
Average(Array);
int max;
max = Max(Array);
System.out.println("The maximum is " +max + ".");
int min;
min = Min(Array);
System.out.println("The minimum is " +min + ".");
}
public static void Average(int[] Array) {
int sum = 0;
int average;
for (int i = 0; i < Array.length; i++)
sum = sum+Array[i];
average=sum/Array.length;
System.out.println("The average is " +average +".");}
public static int Max(int[]Array) {
int max= Array[0];
for (int i = 1; i < Array.length; i++) {
if (Array[i] > max) {
max = Array[i];
}
}
return max;
}
public static int Min(int[]Array) {
int min = Array[0];
for (int i = 1; i < Array.length; i++) {
if (Array[i] < min) {
min = Array[i];
}
}
return min;
public class Bonus1{
public static void main(String[] args) {
int n = Integer.parseInt(args[0]);
int[] numbers = new int[n];
for (int i = 0; i < n; i++ ) {
numbers[i] = i;
}
for (int i = 0; i < n; i++ ) {
int r = i + (int)(Math.random() * (n - i));
int tmp = numbers[i];
numbers[i] = numbers[r];
numbers[r] = tmp;
System.out.print(numbers[i]);
}
int min = Integer.MAX_VALUE;
int count = 0;
while(data.hasNext()){
int y = data.nextInt();
if(y < min){
min = y;
count += 1;
}
}
System.out.println(count);
}
}
this code isn't complete, the first 2 for-loops will generate an array between 0 to a given number in the commandline -1
So for example java Bonus1 10 would first generate an array between 0-9 and then it will shuffle these numbers around so that it creates a random permutation.
the while loop is something I've used before to read input and determine how many times a new lowest number is detected. so for example if I get the permutation 7 8 2 3 4 5 1 0 6 9 it will count 7 as the lowest, then 2 as the lowest and then 1 as the lowest and finally 0 as the lowest, making the total amount of times a new lowest number has been detected 4.
but this only works if I use inputs, I need to use the previously generated output as the input in the same file, is there a clever way to do that?
You should iterate for the array numbers like this.
public static void main(String[] args) {
int n = Integer.parseInt(args[0]);
int[] numbers = new int[n];
for (int i = 0; i < n; i++) {
numbers[i] = i;
}
for (int i = 0; i < n; i++) {
int r = i + (int) (Math.random() * (n - i));
int tmp = numbers[i];
numbers[i] = numbers[r];
numbers[r] = tmp;
System.out.print(numbers[i]);
}
System.out.println();
int min = Integer.MAX_VALUE;
int count = 0;
for (int i = 0; i < n; ++i) {
int y = numbers[i];
if (y < min) {
min = y;
++count;
}
}
System.out.println(count);
}
output:
6457098123
3
I want to get the minimum value and maximum value inside an array. After the user inputs n number of arrays, it will print the minimum and max value inside that array.
Here is an example output
Here is my code so far
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
try {
System.out.println("Enter array size: ");
int n = input.nextInt();
int [] array = new int[n];
int max = getMaxValue(array);
int min = getMinValue(array);
System.out.println("Enter " + n + " elements:");
for (int i = 1; i <= array.length; i++) {
array[i] = input.nextInt();
}
System.out.println("Max Value: " + max);
System.out.println("Min Value: " + min);
} catch (InputMismatchException e) {
System.out.println("INVALID INPUT >> PLEASE INPUT A NUMBER");
}
}
private static int getMaxValue(int[] array) {
int maxValue = array[0];
for (int i = 1; i < array.length; i++){
if (array[i] > maxValue){
maxValue = array[i];
}
}
return maxValue;
}
private static int getMinValue(int[] array) {
int minValue = array[0];
for (int i = 1; i < array.length; i++){
if (array[i] < minValue) {
minValue = array[i];
}
}
return minValue;
}
}
There are a few problems keeping this program from working:
getMinValue and getMaxValue should be called after your input loop
All 3 of your loops index starting from 1, they should start from 0
The input loop repeats until i <= array.length, but it should end at i < array.length
Problem 1 is that these method are called on the empty array.
Problems 2 and 3 will cause an ArrayIndexOutOfBoundsException.
Here's how the corrections would look in your code:
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
try {
System.out.println("Enter array size: ");
int n = input.nextInt();
int [] array = new int[n];
System.out.println("Enter " + n + " elements:");
for (int i = 0; i < array.length; i++) {
array[i] = input.nextInt();
}
int max = getMaxValue(array);
int min = getMinValue(array);
System.out.println("Max Value: " + max);
System.out.println("Min Value: " + min);
} catch (InputMismatchException e) {
System.out.println("INVALID INPUT >> PLEASE INPUT A NUMBER");
}
}
private static int getMaxValue(int[] array) {
int maxValue = array[0];
for (int i = 0; i < array.length; i++){
if (array[i] > maxValue){
maxValue = array[i];
}
}
return maxValue;
}
private static int getMinValue(int[] array) {
int minValue = array[0];
for (int i = 0; i < array.length; i++){
if (array[i] < minValue) {
minValue = array[i];
}
}
return minValue;
}
}
There were 3 problems in your code which are as follows:
int max = getMaxValue(array) int min = getMinValue(array) are called in wrong places
when we initialize an int array the default value present in it is0.
So when you had call getMaxValue().
array[0] = 0 is compared with all rest of the values in the array (which are 0) and from all 0 is the maximum.
Same goes for getMinValue().
You have called the function getMaxValue() and getMinValue() without filling the array,with user input.
you should have used a for loop from 0 to array.length.
for(int index = 0 ; index < array.length ; index++){
array[index] = input.nextInt();
}
Has you would have noticed, I have index staring from 0 to array size.
what you did:
for (int i = 1; i <= array.length; i++) {
array[i] = input.nextInt();
}
this will cause ArrayIndexOutOfBoundException Because array indexing starts from 0 to n-1 and you allowed it to run till 1 to n.
Additionally, the finding of min and max can be done in one function.
by keeping the return type as an array.
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
try {
System.out.println("Enter array size: ");
int n = input.nextInt();
int [] array = new int[n];
System.out.println("Enter " + n + " elements:"); // <-- changed
for (int i = 0; i < array.length; i++) {
array[i] = input.nextInt();
}
int max_min[] = getMax_MinValue(array); // <- notice this.
System.out.println("Max Value: " + max_min[0]);
System.out.println("Min Value: " + max_min[1]);
} catch (InputMismatchException e) {
System.out.println("INVALID INPUT >> PLEASE INPUT A NUMBER");
}finally {
input.close(); // close the scanner
}
}
// return type changed
private static int[] getMax_MinValue(int[] array) {
int maxValue = array[0];
int minValue = array[0];
for (int i = 0; i < array.length; i++){
if (array[i] > maxValue){
maxValue = array[i];
}
if(array[i] < minValue) {
minValue = array[i];
}
}
int min_max[] = {maxValue,minValue}; // min_max[0] has max value and min_max[1] has min value
return min_max;
}
Output:
Enter array size:
8
Enter 8 elements:
5
23
9
14
45
36
42
39
Max Value: 45
Min Value: 5
This is not an appropriate answer.
However as the implementations of getMaxValue & getMinValue have a slight flaw: empty arrays will raise an ArrayIndexOutOfBoundException.
And especially one might use the Stream classes.
private static int getMaxValue(int[] array) {
return IntStream.of(array).max().orElse(0);
}
private static int getMinValue(int[] array) {
return IntStream.of(array).min().orElse(0);
}
max and min yield an OptionalInt, and for empty arrays one may give a default (orElse).
Can somebody help me what's wrong with my codes I'm having trouble with the displaying the largest and the smallest part in the array. Sorry I'm completely new with java. Thanks a bunch
package problem6;
import java.util.Scanner;
public class Problem6 {
public static void main(String[] args) {
int input;
int min = 0;
int max = 0;
Scanner keyboard = new Scanner(System.in);
System.out.println("How many numbers do you want to enter?");
input = keyboard.nextInt();
int array[] = new int[input];
for (int i = 0 ; i < array.length; i++ ) {
System.out.println("Enter number: ");
array[i] = keyboard.nextInt();
}
{
if (input > max)
{
max = input;
}
else if (input <= min)
{
min = input;
}
}
System.out.print("\nLargest: " + max);
System.out.print("\nSmallest:" + min);
}
}
Post you read the value, you need to iterate over the array and try to use your logic of mix/max comparison like:
int min = Integer.MAX_VALUE;//change your assignment of 0 as numbers can be negative
int max = Integer.MIN_VALUE;
for (int number : array) {//use separate for loop or use the same for loop to which you add numbers in array.
if (number > max) {
max = input;
}
else if (number < min) {
min = input;
}
}
With using the same for loop:
int min = Integer.MAX_VALUE;//change your assignment of 0 as numbers can be negative
int max = Integer.MIN_VALUE;
for (int i = 0 ; i < array.length; i++ ) {
System.out.println("Enter number: ");
array[i] = keyboard.nextInt();
if (array[i] > max) {
max = array[i];
}
else if (array[i] < min)
{
min = array[i];
}
}
The errors were
an extra pair of braces, and 2. comparing input-size instead of array elements with min and max.
The probable working code is shown below :-
package problem6;
import java.util.Scanner;
public class Problem6 {
public static void main(String[] args) {
int input;
int min = 0;
int max = 0;
Scanner keyboard = new Scanner(System.in);
System.out.println("How many numbers do you want to enter?");
input = keyboard.nextInt();
int array[] = new int[input];
for (int i = 0 ; i < array.length; i++ ) {
System.out.println("Enter number: ");
array[i] = keyboard.nextInt();
if (array[i] >= max)
{
max = array[i];
}
else if (array[i] <= min)
{
min = array[i];
}
}
System.out.print("\nLargest: " + max);
System.out.print("\nSmallest:" + min);
}
}
You can even try this.
int max=array[0], min=array[0];
for(int x=0; x<array.length; x++){
max = array[x]>max?array[x]:max;
min = array[x]<min?array[x]:min;
}
Set the first array element as min and max first.
You need to have this code:
int max = Integer.MIN_VALUE;
int min = Integer.MAX_VALUE;
for (int i = 0 ; i < array.length; i++ ) {
if (array[i]> max)
{
max = array[i];
}
else if (array[i] <= min)
{
min = array[i];
}
}
System.out.print("\nLargest: " + max);
System.out.print("\nSmallest:" + min);
I'm really stumped trying to find the index of the largest and smallest numbers of a 5x5 array with random numbers up to 1000 generated into them. Here my code:
import java.util.Random;
public class MaxMinArray {
public static void main (String args[]) {
int x=0, y=0, max=0, min=1000;;
int[][] numbers = new int[5][5];
for (x=0; x<numbers.length; x++) { //outer for
for(y=0; y<numbers.length; y++) { //inner for
numbers[x][y]= (int)(Math.random()*1000); //random generator
if(max < numbers[x][y]) //max number
max = numbers[x][y];
if(min>numbers[x][y]) //min number
min = numbers[x][y];
int maxIndex = 0;
for(int index = 1; index<numbers.length; index++)
if(numbers[maxIndex]< numbers[index])
maxIndex = index;
}
}
System.out.println("Max number in array:" + max + " ");
System.out.println("Max number is in" + maxIndex + " ");
System.out.println("Min number in array:" + min + " ");
}
}
You should keep track of both the x and y index of the maximum/minimum element. No need to post-process, it's just a matter of bookkeeping:
if(max < numbers[x][y]) {
max = numbers[x][y];
maxX = x;
maxY = y;
}
Use a Point to keep track of your indices.
Point min = new Point(0, 0);
Point max = new Point(0, 0);
for(int[] row: numbers) {
for(int col= 0; col < row.length; col++) {
if(numbers[row][col] < numbers[min.X][min.Y])
{max.X = row; min.Y = col;}
if(numbers[row][col] > numbers[max.X][max.Y])
{max.X = row; max.Y = col;}
}
}
if(numbers.length > 0) {
System.out.println(numbers[min.X][min.Y] + " is the minimum.");
System.out.println(numbers[max.X][max.Y] + " is the maximum.");
}
for something of this small of scale, a simple double for loop should be the simplest to understand and utilize.
int n=5;
int min = array[0][0];
int[] minIndex = {0,0};
int max = array[0][0];
int[] maxIndex = {0,0};
for (int i=0; i<n; i++)
{
for (int j=0; j<n; j++)
{
if (array[i][j] < min)
{
min = array[i][j];
minIndex[0] = i;
minIndex[1] = j;
}
if (array[i][j] > max) {
max = array[i][j];
maxIndex[0] = i;
maxIndex[1] = j;
}
}
}
For non-trivial dimensions this might be a slow method, but for this size matrix n^2 complexity is fine.
EDIT: WOW, I missed the part about the indices.