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);
Related
The task is: write a program that swaps the maximum and minimum elements of a given array. Print the array before and after this operation.
I am still a huge noob at programming, most of the time I just can't really picture what the codes are doing.
public class problem6 {
public static void main(String[] args) {
int[] arr = new int[15];
for (int i = 0; i < arr.length; i++)
/*
I don't think I really understand incrementation in loops, what exactly do they do? As far as I understand
it is like having an industry line? I suppose 'i' would be the product and '++' would be the thing that
carries 'i' to the be checked one by one? I really need an ape analogy because I can't really visualize it.
*/
arr[i] = (int) (Math.random() * 15);
for (int i = 0; i < arr.length; i++)
System.out.print(arr[i] + ", ");
System.out.println();
int minIndex = 0, maxIndex = 0; //why do we assign min and max to 0 and not any other number?
for (int i = 1; i < arr.length; i++) {
if (arr[minIndex] > arr[i])
minIndex = i;
if (arr[maxIndex] < arr[i])
maxIndex = i;
/*
I see a lot of codes like:
if (arr[minIndex] > arr[i])
minIndex = i;
if (arr[maxIndex] < arr[i])
maxIndex = i;
what purpose does it serve? For the lack of knowledge and from a really noob programmer's perspective
it seems like we are "reassigning" minIndex and maxIndex to 'i', which is probably not what we're actually doing
but I don't know how to describe it other way.
*/
}
System.out.println(minIndex + " " + arr[minIndex]);
System.out.println(maxIndex + " " + arr[maxIndex]);
{
int tmp = arr[minIndex];
arr[minIndex] = arr[maxIndex];
arr[maxIndex] = tmp;
/*
Here again, for the lack of understanding and better way of describing, it seems to me that we are reassigning,
which makes it appear illogical to me, but I'd assume it's not actually "reassigning".
int tmp = arr[minIndex];
arr[minIndex] = arr[maxIndex];
arr[maxIndex] = tmp;
*/
}
for (int i = 0; i < arr.length; i++)
System.out.print(arr[i] + ", ");
System.out.println();
}
}
What is i, what does it do and what does i++ mean:
i is used in this loop to indicate how many times you've looped through said loop.
The ++ is there to do i + 1 after each time you've looped trough the for loop.
For better understanding on how you use i in your example, imagine the array arr being a big book and what you write in the [] is which page you want to open. In the loop you basically flip through the book to each pagenumber in those brackets.
Why does minIndex and maxIndex get set to 0 instead of any other number?
They get set to 0 because we can assume that that is the lowest possible Index in your array. So when the Index gets compared to any other possible number that could be the lowest or highest Index, it always gets set to said lowest or highest Index instead of always having the same value you set because no other value in your array is higher or lower than that.
Why do we make arr[minIndex] assert the same value as arr[maxIndex]?
In your question's title you said that you wanted to swap the highest number in your array with the lowest number. So now that we have found the highest and lowest number in your array these steps switch the two.
If you have any other questions or if any of my descriptions are unclear, just comment under the answer and I'll do my best to help you out. Also, don't look down on yourself so much. Everyone was a "noob" at some point :)
Here is quick fix for you.
Following is complete example of swaps the maximum and minimum elements of a given array.
Input :
Enter elements you want to input in array:
5
Enter all the elements:
10
15
16
1
9
Output :
Element After swaps :
10
15
1
16
9
public static void main(String arg[]) {
Scanner scan = null;
int number;
try {
scan = new Scanner(System.in);
System.out.println("Enter elements you want to input in array: ");
number = scan.nextInt();
int array[] = new int[number];
System.out.println("Enter all the elements:");
for (int i = 0; i < number; i++) {
array[i] = scan.nextInt();
}
int[] resultArray = swap(array);
System.out.println("Element After swaps :");
for (int i : resultArray) {
System.out.println(i);
}
} catch (Exception ex) {
ex.printStackTrace();
} finally {
scan.close();
}
}
public static int[] swap(int[] array) {
int minIndex = 0, maxIndex = 0;
for (int i = 1; i < array.length; ++i) {
if (array[i] < array[minIndex])
minIndex = i;
if (array[i] > array[maxIndex])
maxIndex = i;
}
int t;
if (maxIndex != minIndex) {
t = array[minIndex];
array[minIndex] = array[maxIndex];
array[maxIndex] = t;
}
return array;
}
Hope this solution works.
Please mark as answer if this solution is helpful.
I am new to Java (and coding in general). I need to write a method that gets an integer, creates an array made of random numbers of the length of the integer, range 1-50
(inclusive) and finds the maximum and minimum number.
I was able to fill the array with random numbers. However, my min and max are not printing. I have been looking at this for hours with no luck - any advice would be very helpful! Thank you.
import java.util.Scanner;
import java.util.Random;
class MinMax {
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
//user input a number
System.out.println("Please enter an integer from 1 to 50: ");
int userNum = in .nextInt();
System.out.println();
int x;
int randNum;
int y;
//create random numbers and print
Random r = new Random();
for (int i = 1; i <= userNum; i++) {
randNum = r.nextInt(50) + 1;
System.out.println(randNum);
int[] array = new int[userNum];
for (x = 1; x < 1; x++) {
array[x] = randNum;
System.out.println(array[x]);
//find max
int largest = array[0];
int smallest = array[0];
for (int s = 0; s < array.length; s++) {
largest = array[s];
smallest = array[s];
if (array[s] > largest) {
System.out.println(largest);
//find min
} else if (array[s] < smallest) {
System.out.println(smallest);
} //for
} //if
} //for
} //for
} //main method
} //class
//find max
int largest = array[0];
int smallest = array[0];
for (int s = 0; s < array.length; s++) {
largest = array[s];
smallest = array[s];
if (array[s] > largest) {
System.out.println(largest);
//find min
} else if (array[s] < smallest) {
System.out.println(smallest);
} //for
} //if
Look closely at this code. Inside the loop, you are setting
largest = array[s];
and then immediately checking
if (array[s] > largest)
Of course it's not, you just made them equal!
Put the assignments inside the conditions:
// Remove largest = array[s]
if (array[s] > largest) {
largest = array[s];
}
Similarly for smallest.
Note: I would recommend against commenting on closing braces. Note only is it unnecessary effort, it is confusion-prone: in this snippet of code above, the //for and //if are reversed. Additionally, it doesn't tell you which "if" or "for" it is closing.
Simply looking at the indentation is an easier way.
Your program does not fill the array with random numbers. It creates several arrays and fills each of them with a single number. You should change this part of the program:
Random r = new Random();
for (int i = 1; i <= userNum; i++) {
randNum = r.nextInt(50) + 1;
System.out.println(randNum);
int[] array = new int[userNum];
for (x = 1; x < 1; x++) {
array[x] = randNum;
System.out.println(array[x]);
/* min-max code */
}
}
to this:
Random r = new Random();
int[] array = new int[userNum];
for (int i = 0; i <= userNum; i++) {
array[i] = r.nextInt(50) + 1;
System.out.println(array[i]);
}
/* min-max code */
This will create a single array, fill it with random numbers, and print each element of the array, which seems to be what you intended.
The code that finds the minimum and maximum is also incorrect.
int largest = array[0];
int smallest = array[0];
for (int s = 0; s < array.length; s++) {
largest = array[s];
smallest = array[s];
if (array[s] > largest) {
System.out.println(largest);
} else if (array[s] < smallest) {
System.out.println(smallest);
}
}
You should only set largest or smallest when array[s] is actually the largest or smallest value in the array so far. To check whether or not this is the case, you can use Math.min() and Math.max(), which return the smallest or largest, respectively, of two values.
int largest = array[0];
int smallest = array[0];
for (int s = 0; s < array.length; s++) {
largest = Math.max(array[s], largest);
smallest = Math.min(array[s], smallest);
}
System.out.println(largest);
System.out.println(smallest);
This is what you looking for::
import java.util.Scanner;
import java.util.Random;
public class MinMax {
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
// user input a number
System.out.println("Please enter an integer from 1 to 50: ");
int userNum = in.nextInt();
System.out.println();
int x;
int randNum;
int y;
int[] array = new int[userNum];
// create random numbers and print
Random r = new Random();
for (int i = 1; i <= userNum; i++) {
randNum = r.nextInt(50) + 1;
System.out.println("number " + i + ":: " + randNum);
array[i - 1] = randNum;
}
// print array
for (int s = 0; s < array.length; s++) {
System.out.println("array[" + s + "] number :: " + array[s]);
}
// find max
int largest = array[0];
int smallest = array[0];
for (int s = 0; s < array.length; s++) {
if (array[s] > largest) {
largest = array[s];
// find min
} else if (array[s] < smallest) {
smallest = array[s];
}
}
System.out.println("\nLargets Number:: " + largest);
System.out.println("Smallest Number:: " + smallest);
} // main method
} // class
Don't confuse too much when you are using loops.Some mistakes you done while writing code.
1> You have declared array int[] array = new int[userNum];
in for loop. which mean it will create as much arrays as loop iterate. and not accessible outside loop.
2> Same with variables largest and smallest int largest = array[0];
int smallest = array[0];
3> for (x = 1; x < 1; x++) control never ever enter the loop since your condition x<1 is never satisfy because you have initiated x=1 and and it will never ever be less than 1 as in condition (x<1).
Suggestion :: To find largest you have to traverse through array and check every element for largest and smallest and store it in separate variable rather than printing it at every check.
In my code i have used three for loops::
1>> to generate and print random number. In same loop i'm filling array with generated number.
2>> Here just printing array separately for better presentation in output.
3>> Finding largest and smallest by assigning values in if block if they satisfy condition.
I hope this will help you to understand code.
This is what I have so far, but it only compares number with itself. I need it to compare with all 100 numbers. Thank you!
import java.util.Random;
public class CompSci {
public static void main(String[] args) {
Random generator = new Random();
for (int x = 1; x < 100; x++) {
int num1 = generator.nextInt(100);
System.out.println ("A number from 1 to 100: " +num1);
int numbers[] = new int[]{num1};
int largest = numbers[0];
for(int i = 1; i < numbers.length; i++) {
if(numbers[i] > largest)
largest = numbers[i];
}
System.out.println("Largest Number is: " + largest);
}
}
}
For each iteration of your outer loop you are creating a new array, so move the
int numbers[] array to before the first for loop.
In this case you can set the size of this array to 100 as that will be how many times you will iterate.
Also the value of largest should also be kept outside the loop, and if so then you do not need to loop through all numbers in the array, just the last entered number. In fact you do not even need the number array.
try
import java.util.Random;
public class CompSci {
public static void main(String[] args) {
Random generator = new Random();
int numbers[] = new int[100]; // not even really needed for this exercise
int largest = Integer.MIN_VALUE; // a very small number
for (int x = 1; x < 100; x++) {
int num1 = generator.nextInt(100);
System.out.println ("A number from 1 to 100: " +num1);
numbers [x] = num1;
if(numbers[x] > largest)
{
largest = numbers[x]; //Set if find new largest number
}
System.out.println("Largest Number is: " + largest);
}
}
Note
Also check the javadocs (Thanks #Andreas)
Returns a pseudorandom, uniformly distributed int value between 0
(inclusive) and the specified value (exclusive),
Also, for loop should be x = 0 to x < 100 since the loop is currently run only 99 times and not the intended 100.
You're so close! Divide and conquer the solution into steps:
Generate the randomized set
Create a placeholder for the largest value, and initialize it to the first term in the set.
Visit each subsequent term in the set, and update largest if the term is greater.
Your solution is very close, but a bit tangled up. Let's go over it line-by-line to understand what needs to be adjusted:
// Step 1. Generate the set
for (int x =1; x<100; x++) // iterate from x = 1 to 100 (exclusive)
{ // and for each iteration:
int num1=generator.nextInt(100); // create a random integer num1
System.out.println("A number from 1 to 100: " +num1);
int numbers[] = new int[]{num1}; // create array 'numbers' of length 1,
// and place 'num1' inside the array
// notice how this recreates the set
// for each new number
// Step 2. Instantiate largest to the first random number:
// (notice how this is nested inside Step 1.)
int largest = numbers[0]; // create another integer 'largest' and
// assign to it the 1st element in 'numbers'
// (which is 'num1')
// Step 3. Visit each number (also nested inside Step 1)
for(int i=1; i<numbers.length; i++) // iterate from i=1 (inclusive) until
{ // 'numbers.length' (exclusive)
// note that 'numbers.length' is 1 above, and 'i' is also 1,
// so 'i < numbers.length' is 'false' and the lines below will never execute:
if(numbers[i] > largest) // if the current number in `numbers` is greater
largest = numbers[i]; // update largest
}
System.out.println("Largest Number is: " + largest); // print largest
} // stop step 1
Here's how you may untangle the steps, and perform them in sequence:
// Step 1. Generate the set
int size = 100;
int numbers[] = new int[size]; // create array 'numbers' of length 'size'
for (int x = 0; x < size; x++) // iterate over each element in the array
{
numbers[x] = generator.nextInt(100); // and place a random number in its place
} // stop step 1; now you have a set of 100 random numbers!
// 2. Instantiate largest to the first random number:
int largest = numbers[0];
// 3. visit each remaining number,
for (int i = 1; i < size; i++)
{
// and update largest if current number is greater
if(numbers[i] > largest)
largest = numbers[i];
}
System.out.println ("Largest Number is: " + largest); // print largest
import java.util.Random;
public class CompSci
{
public static void main(String[] args) {
Random generator = new Random();
int numbers[] = new int[100];
int largest = 0;
for(int i = 0;i < 100; i++) {
int num1 = generator.nextInt(100);
numbers[i] = num1;
if(numbers[i] > largest) {
largest = numbers[i];
}
System.out.println("Random number from 1 to 100: " + numbers[i]);
}
System.out.println("Largest Random Number: " + largest);
}
}
I am stuck on my class work:
Create an application containing an array that stores eight integers. The application should
display all the integers, (done)
display all the integers in reverse order,
display the sum of the eight integers, (done)
display all values less than 5,
display the lowest value, (done)
display the highest value, (done)
calculate and display the average, (Done)
display all values that are higher than the calculated average value.
I must use (or attempt to use) an array; also must use at least one loop to "traverse" (move through) the array. This also due # 23:59 mountain standard time tonight
What am I doing wrong?
package numberlistdemo;
import java.util.Arrays;
public class NumberListDemo
{
/**
* #param args the command line arguments
*/
public static void main(String[] args)
{
int n[]= {1,2,3,4,5,6,7,8};
int lowest = 1000;
int highest = 0;
int sum = 0;
int five = 0;
int OverF = 0;
int rev = 0;
int OverAve= 0;
for (int i=0;i<n.length;i++)
{
int cur = n[i];
if (cur < lowest) lowest = cur;
if (cur > highest) highest = cur;
sum += cur;
}
double ave = sum / n.length;
for (int i=0;i<n.length;i++)
{
int cur = n[i];
if (cur > ave) OverAve = cur;
}
for (int i=0;i<n.length;i++)
{
int LowF = n[i];
if (LowF < 5) five = LowF;
if (LowF > 5) OverF = LowF;
}
//3
System.out.println("Total of the Array is " + sum );
//1
System.out.println("The number we are using are " + Arrays.toString(n));
//4
System.out.println("All values lower the 5 are " + five );
////2
for (int counter=n.length - 1; counter >= 0; counter--)
{
System.out.println("The reverse order of the numbers are " + (n[counter]));
}
//5
System.out.println("The lowest value is " + lowest);
//6
System.out.println("The highest value is "+ highest);
//7
System.out.println("The average is " + ave);
//8
System.out.println("All numbers higher than the average are: " + OverAve);
}
}
I get this
Total of the Array is 36
The number we are using are [1, 2, 3, 4, 5, 6, 7, 8]
All values lower the 5 are 4
The reverse order of the numbers are 8
The reverse order of the numbers are 7
The reverse order of the numbers are 6
The reverse order of the numbers are 5
The reverse order of the numbers are 4
The reverse order of the numbers are 3
The reverse order of the numbers are 2
The reverse order of the numbers are 1
The lowest value is 1
The highest value is 8
The average is 4.0
All numbers higher than the average are: 8
Sample loop to obtain sum, lowest, and highest integer from an array
int lowest = 1000;
int highest = 0;
int sum = 0;
for (int i = 0; i < array.length; ++i) {
int cur = array[i];
if (cur < lowest) lowest = cur;
if (cur > highest) highest = cur;
sum += cur;
}
Edit: the latest code updates made some progress, but likely do not quite meet the specified requirements. There are some difficulties in knowing the full requirement (e.g., output format).
Output Only
The current example is displaying the output (one entry per line). It is not clear if one only needs to display the output or actually reverse the array. If the only requirement is to output the reversal, the numbers larger than 5 and larger than 8, the the following three loops will work. One is mostly already in the suggested code.
System.out.println("The reversed array is: ");
for (int counter < n.length - 1; counter >= 0; counter--) {
System.out.print(n[counter] + " ");
}
System.out.println();
Note that these two should probably be in a method
final int lessThan = 5;
System.out.println("The numbers in the array less than " + lessThan + " are: ");
for (int i = 0; i < n.length; ++i) {
if (n[i] < lessThan) {
System.out.print(n[i] + " ");
}
}
System.out.println();
System.out.println("The numbers in the array greater than the mean " + ave + " are: ");
for (int i = 0; i < n.length; ++i) {
if (n[i] > ave) {
System.out.print(n[i] + " ");
}
}
System.out.println();
Create a new reversed array
It would make more sense for the assignment to require actually reversing the array. In that case, there are a couple of approaches. Probably the easiest is to create a new array and reverse the elements into it. Essentially it is the same loop as above, but placing the elements of n into the array rather than outputing them to the screen. (Note: #Debosmit proposed an example that does not require the additional index variable).
int[] reversed = new int[n.length];
int idx = 0;
for (i = n.length - 1; i >= 0; --i) {
reversed[idx++] = n[i]];
}
Later then one can use the same output approach as was used for displaying all of the original entries:
System.out.println("The reversed array is: " + Arrays.toString(reversed));
What is the error message?
since you are not using curly braces{ } your local variable int i will only exist within these lines:
for (int i=0;i<n.length;i++)
sum = sum + n[i];
and NOT these:
double rev = n.length - i - 1;
boolean l = (n[i] < 5);
Ah! Well... I'll contribute. Here is how to reverse...
// note this will change the original array
for(int i = 0 ; i < n.length ; i++) {
int t = n[i];
n[i] = n[n.length - 1 - i];
n[n.length - 1 - i] = t;
}
// this will not change the original array
int[] newArr = new int[n.length];
for(int i = 0 ; i < n.length ; i++) {
newArr[n.length - 1 - i] = n[i];
}
// you can now return `newArr` or something since it is `n` reversed
Now to look at all values that are higher than the calculated average value. I think you already have the sum of the numbers. Lets call it sum. avg = sum/n.length.
for(int i = 0 ; i < n.length ; i++) {
if(n[i] > avg)
System.out.println(n[i]);
}
All numbers less than 5.
for(int i = 0 ; i < n.length ; i++) {
if(n[i] < 5)
System.out.println(n[i]);
}
In the future, please don't come here with your homework before trying to do it yourself. Thanks! :)
I have to find the lowest number in an array. It works when I manually make an array, but when I use a scanner to get numbers from the user and they put in a negative number, it does not consider the negative sign and acts as if the number is a positive number. Is there something scan.nextInt does to negative numbers that causes this?
System.out.println("Enter an array size.");
size = scan.nextInt();
int[] numbers = new int[size];
System.out.println("Enter each integer in the array and press Enter after each one.");
for(int i = 0; i < size; i++)
{
numbers[i] = scan.nextInt();
}
for(int j = 0; j < size; j++)
{
smallest = numbers[0];
if (numbers[j] < smallest)
{
smallest = numbers[j];
}
}
System.out.println("Smallest Number is " + smallest);
This is the code for reference
You reset the smallest variable every loop.
Try initializing it before the loop.
smallest = numbers[0];
for(int j = 0; j < size; j++)
{
if (numbers[j] < smallest)
{
smallest = numbers[j];
}
}
You have to initialize your smallest out of the loop, preferably at the beginning. And if you are going to find the smallest, assign it a big value (if largest, assign a very small value);
int smallest = Integer.MAX_VALUE;
Integer.MAX_VALUE is the greatest possible value that you can assign to an integer in Java.
And always remember to release the resources. You have to close the scanner object when you're done with it.
scan.close(); // always release resources
Here is the demo code;
Demo Code
import java.util.Scanner;
public class FindLowest {
public static void main(String[] args) {
// initialization of variables
int size;
Scanner scan = new Scanner(System.in);
int smallest = Integer.MAX_VALUE;
System.out.println("Enter an array size.");
size = scan.nextInt();
int[] numbers = new int[size];
System.out.println("Enter each integer in the array and press Enter after each one.");
for (int i = 0; i < size; i++) {
numbers[i] = scan.nextInt();
}
scan.close(); // always release resources
for (int j = 0; j < size; j++) {
// smallest = numbers[0]; // dont initialize here, initialize at beginning
if (numbers[j] < smallest) {
smallest = numbers[j];
}
}
System.out.println("Smallest Number is " + smallest);
}
}
Output Sample
Enter an array size.
5
Enter each integer in the array and press Enter after each one.
1
-2
3
-4
5
Smallest Number is -4