Hi so I'm new at java programming and i'm currently at learning array. So what i'm trying to do is find the maximum and minimum value of an array but for some reason i cant find the minimum value but i can find the maximum value.
Here is my output:
Enter the number of elements: 5
Enter a number: 1
Enter a number: 2
Enter a number: 3
Enter a number: 4
Enter a number: 5
The maximum number is:5
The minimum number is: 0
I've used the same statement for getting the max value by only changing the operator. But somehow the output is always zero.
Here is my code:
import java.util.Scanner;
public class Main
{
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter the number of elements: ");
int elements = input.nextInt();
int [] array = new int[elements];
int max = array[0];
int min = array[0];
for(int i = 0; i<elements; i++){
System.out.print("Enter a number: ");
array[i] = input.nextInt();
if(array[i]>max){
max = array[i];
}
if(array[i]<min){
min = array[i];
}
}
System.out.print("The maximum number is:" + max);
System.out.println();
System.out.print("The minimum number is: " + min);
}
}
Any help would be appreciated thanks!
int min = array[0];
This statement is executed at a time when array[0] is zero.
You have not read any values at this point, so initialize your min and max values with:
int max = Integer.MIN_VALUE;
int min = Integer.MAX_VALUE;
In fact, you don't need the array at all, since you don't use it after the loop. Just assign the scanner result to an int variable, declared inside the loop.
Assing highest value to min and lowest value to max
min = Integer.MAX_VALUE;
max = Integer.MIN_VALUE;
When you allocate memory using new operator,
int [] array = new int[elements];
each element of array is initialized to zero.
So when you do int min=array[0], min is assigned value 0. Then on comparing with 1,2,3,4 and 5 ,min is smallest and hence does not change.
To solve this,
First input all the elements in array using for loop , then initialize min and max to array[0]
Try this
import java.util.Scanner;
public class Main
{
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter the number of elements: ");
int elements = input.nextInt();
int [] array = new int[elements];
for(int i = 0; i<elements; i++){
System.out.print("Enter a number: ");
array[i] = input.nextInt();
}
int max = array[0];
int min = array[0];
for(int i = 0; i<elements; i++){
if(array[i]>max){
max = array[i];
}
if(array[i]<min){
min = array[i];
}
}
System.out.print("The maximum number is:" + max);
System.out.println();
System.out.print("The minimum number is: " + min);
}
}
The default initial value of an Integer is 0.
for this reason when checking if it is bigger than the input value the default value stays the same
Why do you need an array for this in the first place?
Scanner console = new Scanner(System.in);
int entries = console.nextInt();
int min = Integer.MAX_VALUE;
int max = Integer.MIN_VALUE;
for(int i = 0; i < entries; i++){
int temp = console.nextInt();
if(temp < min) {
min = temp;
}
if (temp > max) {
max = temp;
}
}
Related
package HighLow;
import javax.swing.JOptionPane;
public class HighLow {
public static void main (String[]args) {
int [][] arr= new int[3][4];
int smallest=arr[0][0];
int largest= arr[0][0];
int i = 0;
int j = 0;
{
arr[i][j] = Integer.parseInt(JOptionPane.showInputDialog("Please enter 12 numbers: "));
{
if (arr[i][j] < smallest) {
smallest = arr[i][j];
}
if (arr[0][0] > largest) {
largest = arr[i][j];
}
{
JOptionPane.showMessageDialog(null, "The smallest value in the Array is:" + smallest);
JOptionPane.showMessageDialog(null, "The largest value in the Array is:" + largest);
}
}
}}}
How can I find the lowest and highest number in 2d array?
I'm getting an error with my code? what seems to be wrong?
I just need to find the highest and lowest among the 12 numbers user will input. here is what I have so far.
How can I find the lowest and highest number in 2d array?
I'm getting an error with my code? what seems to be wrong?
I just need to find the highest and lowest among the 12 numbers user will input. here is what I have so far.
You do not have a loop to take in your array and therefore are receiving an error. To take in the input of the Array use this
for (int i = 0;i<3;i++)
for (int j = 0;j<4;j++)
arr[i][j] = Integer.parseInt(JOptionPane.showInputDialog("Please enter 12 numbers: "));
Therefore you will have the box outputted 12 times for the user to input 12 Integers and then once you have the Array just run a simple sort to get the smallest and the largest.
int smallest = arr[0][0];
int largest = arr[0][0];
for (int i = 0;i<3;i++)
for (int j = 0;j<4;j++) {
if (arr[i][j]<smallest)
smallest = arr[i][j];
else if(arr[i][j]>largest)
largest = arr[i][j];
}
}
Final Code being
public class Solution {
public static void main (String[]args) {
int [][] arr= new int[3][4];
for (int i = 0;i<3;i++)
for (int j = 0;j<4;j++)
arr[i][j] = Integer.parseInt(JOptionPane.showInputDialog("Please enter 12 numbers: "));
int smallest = arr[0][0];
int largest = arr[0][0];
for (int i = 0;i<3;i++)
for (int j = 0;j<4;j++) {
if (arr[i][j]<smallest)
smallest = arr[i][j];
else if(arr[i][j]>largest)
largest = arr[i][j];
}
}
JOptionPane.showMessageDialog(null, "The smallest value in the Array is:" + smallest);
JOptionPane.showMessageDialog(null, "The largest value in the Array is:" + largest);
}
}
The error is mainly in the initialization part where you have assumed the element in the first row and first column to be either the minimum or maximum element in the array.
You have to initialize the minimum value of the array with a value that is sure to be higher than all the values in the array, why? because only then will there be an update to the actual minimum value of the array, so for example if you set minimum to be 1000 then if the actual minimum of the array is 300, it would get updated. But if you set your minimum to be for example 30 then 300 which is the actual minimum wont get logged and there would be an error.
The absolute opposite applies to the initialization of the largest value of the array. While initializing, safe ball park estimates usually work so carry out the initializations accordingly.
Personally, I don't think you should use JOptionPane to get data from the user and to display data to the user in a Java console application such as yours. I prefer to use Scanner.
(Below code demonstrates. Notes after the code.)
Note that calling a method of JOptionPane will launch the Event Dispatch Thread (EDT) which means that your application will not terminate – unless you add System.exit(0);.
package HighLow;
public class HighLow {
public static void main(String[] args) {
Scanner stdin = new Scanner(System.in);
System.out.print("Please enter 12 numbers: ");
String line = stdin.nextLine();
String[] numbers = line.split(" ");
int k = 0;
int[][] arr = new int[3][4];
int smallest = Integer.MAX_VALUE;
int largest = Integer.MIN_VALUE;
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 4; j++) {
arr[i][j] = Integer.parseInt(numbers[k++]);
if (arr[i][j] < smallest) {
smallest = arr[i][j];
}
if (arr[i][j] > largest) {
largest = arr[i][j];
}
}
}
System.out.println("The smallest value in the Array is: " + smallest);
System.out.println("The largest value in the Array is: " + largest);
}
}
I assume that the user enters twelve numbers separated by a space in a single line.
Method split returns an array of size twelve where every element is one of the entered numbers.
I initialize smallest to the largest int which guarantees that the first int that I compare it to is guaranteed to be smaller.
Similarly for largest. I initialize it to the smallest possible int.
You need a loop in order to populate all the elements of arr.
Here is output from a sample run of the above code.
Please enter 12 numbers: 1 2 3 4 5 6 7 8 9 0 -1 -2
The smallest value in the Array is: -2
The largest value in the Array is: 9
EDIT
Since you claim that JOptionPane is required, below code uses JOptionPane.
String line = JOptionPane.showInputDialog("Please enter 12 numbers: ");
String[] numbers = line.split(" ");
int k = 0;
int[][] arr = new int[3][4];
int smallest = Integer.MAX_VALUE;
int largest = Integer.MIN_VALUE;
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 4; j++) {
arr[i][j] = Integer.parseInt(numbers[k++]);
if (arr[i][j] < smallest) {
smallest = arr[i][j];
}
if (arr[i][j] > largest) {
largest = arr[i][j];
}
}
}
JOptionPane.showMessageDialog(null, "The smallest value in the Array is:" + smallest);
JOptionPane.showMessageDialog(null, "The largest value in the Array is:" + largest);
System.exit(0);
I just want to add a simple where I can add an input line part by user instead of hard code defining an array. So I can just enter a couple number as a part of an array.
Here is my original code:
public class Test {
public static void main(String[] args) {
System.out.println("Largest in given array is " + max());
}
static int array[] = {10, 324, 45, 90, 9808};
// Method to find maximum in arr[]
public static int max() {
int i;
// Initialize maximum element
int max = array[0];
// Traverse array elements from second and
// compare every element with current max
for (i = 1; i < array.length; i++)
if (array[i] > max)
max = array[i];
return max;
}
}
My logic is this, tell me if I'm right or not
I need to add import java.util.Scanner; and then enter Scanner input = new Scanner(System.in);
But next part confuses me, should I change the max() into a string?
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
System.out.println("Largest in given array is " + max(int[] array));
}
Scanner input = new Scanner(System.in);
static int array[] = {10, 324, 45, 90, 9808};
// Method to find maximum in arr[]
public static int max(int[] array) {
int x;
// Initialize maximum element
int max = array[0];
// Traverse array elements from second and
// compare every element with current max
for (x = 1; x < array.length; x++)
if (array[x] > max)
max = array[x];
return max;
}
}
I'd recommend a re-evaluation of your general design before adding user input. Using a global array variable is unnecessary and arbitrarily restricts the ability of the max function to perform work on anything other than the hard-coded global array. max should accept a parameter array to operate on; this enables reusability.
Your max function's logic seems accurate but will crash the program on empty input arrays.
When handling user input, you may want to be able to respond to variable sizes. For this, using an ArrayList is the easiest way to go.
I also recommend initializing loop counters such as i in loop scope.
Here's a possible rewrite on the way to dynamic arrays that you can use:
import java.util.*;
class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int arr[] = new int[8];
for (int i = 0; i < arr.length; i++) {
System.out.print("Enter an integer: ");
arr[i] = in.nextInt();
}
System.out.println("Largest in given array is " + max(arr));
}
public static int max(int arr[]) {
if (arr.length == 0) {
return -1;
}
int max = arr[0];
for (int i = 1; i < arr.length; i++) {
if (arr[i] > max) {
max = arr[i];
}
}
return max;
}
}
Output:
Enter an integer: 1
Enter an integer: 2
Enter an integer: 3
Enter an integer: 6
Enter an integer: 5
Enter an integer: 3
Enter an integer: 4
Enter an integer: 1
Largest in given array is 6
What I'm trying to do is get a set of numbers from the user, the console will print out the second highest number in english and the second lowest number in spanish.
First I'm trying to get the input from user, put it in an array and grab the second highest and second lowest value of the components. But I can't figure out how to grab ones I need.
public static void main(String[] args) {
//get the length from user
int length;
Scanner input = new Scanner(System.in);
System.out.println("How many variables are you going to enter?: ");
length = input.nextInt();
//allocate array for that length
int[] variables = new int[length];
for(int counter = 0; counter < length; counter++) {
System.out.println("Enter variable: ");
variables[counter] = input.nextInt();
}
input.close();
//print the variables
System.out.println("Your variables are");
for(int counter = 0; counter < length; counter++) {
System.out.println(variables[counter]);
}
}
System.out.println("------------------");
Arrays.sort(variables); //sort array
System.out.println(variables[1]); //2nd lowest value
System.out.println(variables[variables.length-2]); //2nd highest value
try this brother
add this to your code
class Demo
{
public static void findNum(int arr[]){
int largest = arr[0], second_largest = arr[0];
int minimum = are[0], second_minimum = are[0];
for(int i=0;i<arr.length;i++){
if(arr[i] >= largest){
second_largest = largest;
largest = arr[i];
}
else if(arr[i]>second_largest){
second_largest = arr[i];
}
if(arr[i] <= minimum){
second_minimum = minimum;
minimum = arr[i];
}
else if(arr[i]<second_minimum){
second_minimum = arr[i];
}
}
System.out.println("Second Largest = " + second_largest + " Second_minimum = "+second_minimum);
}
public static void main (String[] args) throws java.lang.Exception
{
int arr[] = {5,3,2,1,8,77};
findNum(arr);
}
}
You can do something like this if you're particular about not sorting your original array.
My code does not give errors, however it is not displaying the minimum and maximum values. The code is:
Scanner input = new Scanner(System.in);
int array[] = new int[10];
System.out.println("Enter the numbers now.");
for (int i = 0; i < array.length; i++) {
int next = input.nextInt();
// sentineil that will stop loop when 999 is entered
if (next == 999) {
break;
}
array[i] = next;
// get biggest number
getMaxValue(array);
// get smallest number
getMinValue(array);
}
System.out.println("These are the numbers you have entered.");
printArray(array);
// getting the maximum value
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];
}
}
return maxValue;
}
// getting the miniumum value
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];
}
}
return minValue;
}
//this method prints the elements in an array......
//if this case is true, then that's enough to prove to you that the user input has //been stored in an array!!!!!!!
public static void printArray(int arr[]) {
int n = arr.length;
for (int i = 0; i < n; i++) {
System.out.print(arr[i] + " ");
}
}
Do I need a system.out.println() to display it, or should the return work?
getMaxValue(array);
// get smallest number
getMinValue(array);
You are calling the methods but not using the returned values.
System.out.println(getMaxValue(array));
System.out.println(getMinValue(array));
You can try this too, If you don't want to do this by your method.
Arrays.sort(arr);
System.out.println("Min value "+arr[0]);
System.out.println("Max value "+arr[arr.length-1]);
Imho one of the simplest Solutions is:
-
//MIN NUMBER
Collections.sort(listOfNumbers);
listOfNumbers.get(0);
//MAX NUMBER
Collections.sort(listOfNumbers);
Collections.reverse(listOfNumbers);
listOfNumbers.get(0);
Here is the working code to find the min and max in the array.I hope you will find it helpful:
import java.util.Random;
import java.util.Scanner;
public class FindMin {
public static void main(String[] args){
System.out.println("Main Method Started");
Scanner in = new Scanner(System.in);
System.out.println("Enter the size of the arr");
int size = in.nextInt();
System.out.println("Enter the maximum value of the arr");
int max = in.nextInt();
int [] arr = initializeArr(max, size);
print(arr);
findMinMax(arr);
System.out.println("Main Method Ended");
}
public static void print(int[] arr){
for(int val:arr){
System.out.print(val + " ");
}
System.out.println();
}
public static int[] initializeArr(int max,int size){
Random random = new Random();
int [] arr = new int[size];
for(int ii=0;ii<arr.length;ii++){
arr[ii]=random.nextInt(max);
}
return arr;
}
public static void findMinMax(int[] arr){
int min=arr[0];
int max=arr[0];
for(int ii=0;ii<arr.length;ii++){
if(arr[ii]<min){
min=arr[ii];
}
else if(arr[ii]>max){
max=arr[ii];
}
}
System.out.println("The minimum in the arr::"+min);
System.out.println("The maximum in the arr::"+max);
}
}
Sum, Maximum and Minimum value of an Array in One Line
public static void getMinMaxByArraysMethods(int[] givenArray){
//Sum of Array in One Line
long sumofArray = Arrays.stream(givenArray).sum();
//get Minimum Value in an array in One Line
int minimumValue = Arrays.stream(givenArray).min().getAsInt();
//Get Maximum Value of an Array in One Line
int MaxmumValue = Arrays.stream(givenArray).max().getAsInt();
}
You just throw away Min/Max values:
// get biggest number
getMaxValue(array); // <- getMaxValue returns value, which is ignored
// get smallest number
getMinValue(array); // <- getMinValue returns value, which is ignored as well
You can do something like
...
array[i] = next;
System.out.print("Max value = ");
System.out.println(getMaxValue(array)); // <- Print out getMaxValue value
System.out.print("Min value = ");
System.out.println(getMinValue(array)); // <- Print out getMinValue value
...
You are doing two mistakes here.
1. calling getMaxValue(),getMinValue() methods before array initialization completes.
2.Not storing return value returned by the getMaxValue(),getMinValue() methods.
So try this code
for (int i = 0 ; i < array.length; i++ )
{
int next = input.nextInt();
// sentineil that will stop loop when 999 is entered
if (next == 999)
break;
array[i] = next;
}
// get biggest number
int maxValue = getMaxValue(array);
System.out.println(maxValue );
// get smallest number
int minValue = getMinValue(array);
System.out.println(minValue);
your maximum, minimum method is right
but you don't print int to console!
and... maybe better location change (maximum, minimum) methods
now (maximum, minimum) methods in the roop. it is need not.. just need one call
i suggest change this code
for (int i = 0 ; i < array.length; i++ ) {
int next = input.nextInt();
// sentineil that will stop loop when 999 is entered
if (next == 999)
break;
array[i] = next;
}
System.out.println("max Value : " + getMaxValue(array));
System.out.println("min Value : " + getMinValue(array));
System.out.println("These are the numbers you have entered.");
printArray(array);
Yes you need to use a System.out.println. But you are getting the minimum and maximum everytime they input a value and don't keep track of the number of elements if they break early.
Try:
for (int i = 0 ; i < array.length; i++ ) {
int next = input.nextInt();
// sentineil that will stop loop when 999 is entered
if (next == 999)
break;
array[i] = next;
}
int length = i;
// get biggest number
int large = getMaxValue(array, length);
// get smallest number
int small = getMinValue(array, length);
// actually print
System.out.println( "Max: " + large + " Min: " + small );
Then you will have to pass length into the methods to determine min and max and to print. If you don't do this, the rest of the fields will be 0 and can mess up the proper min and max values.
Here you haven't print the max and min values. Print the max and min values in the getMaxVal and getMin val methods or after the call. This is the output.
Enter the numbers now.
5
Max: 5
Min: 0
3
Max: 5
Min: 0
7
Max: 7
Min: 0
3
Max: 7
Min: 0
90
Max: 90
Min: 0
43
Max: 90
Min: 0
100
Max: 100
Min: 0
45
Max: 100
Min: 0
23
Max: 100
Min: 0
22
Max: 100
Min: 3
These are the numbers you have entered.
5 3 7 3 90 43 100 45 23 22
Also when you are declaring an array, it has all 0s initially.
import java.util.*;
class Maxmin
{
public static void main(String args[])
{
int[] arr = new int[10];
Scanner in = new Scanner(System.in);
int i, min=0, max=0;
for(i=0; i<=arr.length; i++)
{
System.out.print("Enter any number: ");
arr[i] = in.nextInt();
}
min = arr[0];
for(i=0; i<=9; i++)
{
if(arr[i] > max)
{
max = arr[i];
}
if(arr[i] < min)
{
min = arr[i];
}
}
System.out.println("Maximum is: " + max);
System.out.println("Minimum is: " + min);
}
}
//To Find Max and Min value in an array without sorting in java
import java.util.Scanner;
import java.util.*;
public class MaxMin_WoutSort {
public static void main(String args[])
{
int n,max=Integer.MIN_VALUE,min=Integer.MAX_VALUE;
System.out.println("Enter the number of elements: ");
Scanner sc = new Scanner(System.in);
int[] arr = new int[sc.nextInt()]; //U can't say static or dynamic.
//UnWrapping object sc to int value;sc.nextInt()
System.out.println("Enter the elements: ");
for(int i=0;i<arr.length;i++) //Loop for entering values in array
{
int next = sc.nextInt();
arr[i] = next;
}
for(int j=0;j<arr.length;j++)
{
if(arr[j]>max) //Maximum Condition
max = arr[j];
else if(arr[j]<min) //Minimum Condition
min = arr[j];
}
System.out.println("Highest Value in array: " +max);
System.out.println("Smallest Value in array: "+min);
}
}
I have updated your same code please compare code with your's original code :
public class Help {
public static void main(String args[]){
Scanner input = new Scanner(System.in);
int array[] = new int[10];
System.out.println("Enter the numbers now.");
for (int i = 0; i < array.length; i++) {
int next = input.nextInt();
// sentineil that will stop loop when 999 is entered
if (next == 999) {
break;
}
array[i] = next;
}
System.out.println("These are the numbers you have entered.");
printArray(array);
// get biggest number
System.out.println("Maximum: "+getMaxValue(array));
// get smallest number
System.out.println("Minimum: "+getMinValue(array));
}
// getting the maximum value
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];
}
}
return maxValue;
}
// getting the miniumum value
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];
}
}
return minValue;
}
//this method prints the elements in an array......
//if this case is true, then that's enough to prove to you that the user input has //been stored in an array!!!!!!!
public static void printArray(int arr[]) {
int n = arr.length;
for (int i = 0; i < n; i++) {
System.out.print(arr[i] + " ");
}
}
}
I am trying to create a program that sorts user inputted integers from greatest to least. Also I need to find a way to print the maximum and minimum numbers. The code was sorting fine when I had defined values but now that I have switched it to user input it sends back "0"s for some reason. This is my code
import java.util.Scanner;
public class SortInteger {
public static void main(String [] args)
{
Scanner input = new Scanner(System.in);
System.out.println("Please input three numbers");
int num = input.nextInt();
int number [] = new int [num]; //Sorting Array
int temp;
boolean correct = false; // Forces the sorting to continue till the numbers are in order
while(correct ==false){
correct = true;
for(int i = 0; i>number.length-1; i++ ){
if(number [i] > number [i+1]){
temp = number [i+1];
number [i+1] = number[i];
number[i]= temp;
correct = false;
}
}
}
for(int i = 0; i<number.length-1; i++){ //outputs the array to user
System.out.println(number[i]);
}
}
}
you have taken only one number
int num = input.nextInt();
and you are using it for array size :
int number [] = new int [num];
but in rest of the code you haven't taken any input so your array is empty.
Code::
import java.util.*;
class test{
public static void main(String [] args)
{
Scanner input = new Scanner(System.in);
System.out.println("Please input three numbers");
int num1 = input.nextInt();
int num2 = input.nextInt();
int num3 = input.nextInt();
int number [] = {num1,num2,num3}; //Sorting Array
int temp;
boolean correct = false; // Forces the sorting to continue till the numbers are in order
while(correct ==false){
correct = true;
for(int i = 0; i<number.length-1; i++ ){
if(number [i] > number [i+1]){
temp = number [i+1];
number [i+1] = number[i];
number[i]= temp;
correct = false;
}
}
}
for(int i = 0; i<number.length; i++){ //outputs the array to user
System.out.println(number[i]);
}
}}
Output::
Please input three numbers
1
5
4
1
4
5
you are only initializing your array. you never initialized your array with elements, thus your array elements get default values.
System.out.println("Please enter size");
int num = input.nextInt();
int number [] = new int [num]; //Sorting Array
for(int i=0; i<number.length; i++){
System.out.println("Please enter element at index " + i);
number[i] = input.nextInt()
}
As others pointed out you need to populate your array with multiple values, currently you are requesting only one int.
Also, are you sure that works? Should't your first for loop read:
for(int i = 0; i<number.length-1; i++ )
Instead of:
for(int i = 0; i>number.length-1; i++ )
On a side note, it looks to me that your sorting algorithm is O(n2) you may want to look into mergesort and quicksort.