Java - Finding Largest and Smallest Numbers using an Array - java

I am supposed to make a program that takes 10 numbers from a user input, find the largest and smallest number and display all the inputs from the user. This program does use an array. Here is my code:
import java.util.Scanner; // program uses Scanner
public class ArrayTester {
// begin execution
public static void main(String[] args) {
// declare and create array object
// declare smallest and largest int variables
int[] numbers;
numbers = new int[10];
int smallest = numbers[0], largest = numbers[0];
// create Scanner object
Scanner input = new Scanner(System.in);
// prompt user
System.out.print("Please enter 10 numbers: \n");
// use for loop to obtain user input
for (int counter = 0; counter < numbers.length; counter++) {
numbers[counter] = input.nextInt();
} // end obtaining input
// enhanced for loop to find largest and smallest values
for (int i : numbers) {
if (numbers[i] < smallest) {
smallest = numbers[i];
} // end finding smallest
else if (numbers[i] > largest) {
largest = numbers[i];
} // end finding largest number
} // end finding largest and smallest values
// for loop to print user input
System.out.printf("%s%8s\n", "Index", "Input");
for (int counter = 0; counter <= numbers.length; counter++) {
System.out.printf("%5d%8d\n", counter, numbers[counter]);
} // end printing input values
// print smallest and largest numbers
System.out.printf("Smallest number: %d\nLargest number: %d\n", smallest, largest);
System.out.print("Programmed by Christian Lapinig");
} // end main
} // end ArrayTester
At this point I am able to obtain user inputs, but I run into this problem:
Please enter 10 numbers:
454
392
33
41
6
44
39
21
12
2
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 454
at ArrayTester.main(ArrayTester.java:32)
Would I need a try and catch block to fix this?

Your problem is related to the way you use the for-loop as already stated in the other answers. A shorter approach in Java 8 though, would be using a stream:
IntStream.of(numbers).max() and IntStream.of(numbers).min()

A try-catch would just swallow the exception. Your problem is that the enhanced for loop is iterating over the values of the array, but you're treating it like it's the index, so you check numbers[454] and immediately blow up because you're outside the length of the array.
Either iterate over the indexes, or just work with the values directly:
for (int i : numbers) {
if (i < smallest) {
smallest = i;
} // end finding smallest
else if (i > largest) {
largest = i;
} // end finding largest number
} // end finding largest and smallest values

for (int counter = 0; counter <= numbers.length; counter++)
You put =<, instead you should put <. if counter equals to length, it tries to reach out of range because indexes start from zero.

CHange
for (int i : numbers) {
to
for (int i=0;i<numbers.length;i++) {

Your problem is in this loop:
for (int i : numbers) {
This loop means iterates over the elements of the array, not its indexes. So, you can say:
for (int a : numbers) {
if(a > ...) {
....
}
Alternatively you can use array index like the following"
for (int i = 0; i < numbers.lenth; i++) {
if(numbers[i] > ...) {
.....
}

Change it to :
for (int i=0 ;i< numbers.length; i++) {
if (numbers[i] < smallest) {
smallest = numbers[i];
} // end finding smallest
else if (numbers[i] > largest) {
largest = numbers[i];
} // end finding largest number
}
AND <= to <
for (int counter = 0; counter < numbers.length; counter++) {
System.out.printf("%5d%8d\n", counter, numbers[counter]);
}
Try catch block will simply handle your error in a graceful way . It won't solve your problem.

In java 8, you can obtain an IntStream and get the summary statistics.
final IntSummaryStatistics stats = IntStream.of(numbers).summaryStatistics();

As many people pointed out, you are using the values of your for-each loop as and index, meaning your code tries to access the position of whatever number your user inputs in your array.
So to fix it, you just need to do
smallest = i;
and
largest = i;

Related

How to count inputs in an array in java

I have n inputs.
these inputs are numbers from 1 to 100.
I want to output the number that appears less than the other ones; also if there are two numbers with the same amount of appearance, I want to output the number that is less than the other one.
I wrote this code but it doesn't work!
Scanner scanner = new Scanner(System.in);
int n=scanner.nextInt(), max=0 , ans=-1;
int[] counter = new int[n];
for(int i=0; i<n; i++)
counter[scanner.nextInt()]+=1;
for(int j=1; j<=100; j++){
if(counter[j]>max)
max=counter[j];
}
for (int i=1; i<=max; i++){
if(counter[i]>0)
if(ans==-1 || counter[ans]>counter[i] || (counter[ans] == counter[i] && i<ans))
ans=i;
}
System.out.print(ans);
There’s a couple of problems with your code, but the main one is the last for loop: You are trying to find the first (ie lowest) number whose counter is equal to max, so your loop should be from 1 to n, not 1 to max.
Another problem is if you are using the number, which is in the range 1-n, as your array index, you need an array of size n+1, not n.
I pinched this from another question regarding the title of yours:
i = input.nextInt (); while (i != 0) { counts [i]++; i = input.nextInt (); } That method increments the number at the position of the user input in the counts array, that way the array holds the number of times a number occurs in a specific index, e.g. counts holds how often 3 occurs.
counter array should contain frequency values for the numbers from 1 to 100 inclusive.
That is, either a shift by 1 should be used when counting the frequency:
int[] counter = new int[100];
for (int i = 0; i < n; i++) {
counter[scanner.nextInt() - 1]++;
}
or 101 may be used as the length of counter array thus representing values in the range [0..100], without shifting by 1.
int[] counter = new int[101];
for (int i = 0; i < n; i++) {
counter[scanner.nextInt()]++;
}
The minimal least frequent number can be found in a single loop (assuming that the counter length is 101).
int minFreq = 101, answer = -1;
for(int j = 1; j <= 100; j++) {
if (counter[j] > 0 && counter[j] < minFreq) { // check valid frequency > 0
minFreq = counter[j];
answer = j;
}
}
System.out.println(answer);
For a wider range of input values (e.g. including negative values) of a relatively small count it is better to use a hashmap instead of a large sparse array.

How to print out even-numbered indexes for arrays in Java?

I'm supposed to write a program using for loops that print out the even indexes of my array. For example, if I create an array that has 10 numbers, it will have indexes from 0-9 so in that case I would print out the numbers at index 2, 4, 6 and 8. This is what I wrote so far but it doesn't work. Please note that I am not trying to print out the even numbers of the array. All I want are the even indexes.
Example I enter the following array: 3,7,5,5,5,7,7,9,9,3
Program output:
5 // (the number at index 2)
5 // (the number at index 4)
7 // (the number at index 6)
9 // (the number at index 8)
My Code:
public class Arrayevenindex
{
public static void main(String[] args)
{
int number; // variable that will represent how many elements the user wants the array to have
Scanner key = new Scanner(System.in);
System.out.println(" How many elements would you like your array to have");
number = key.nextInt();
int [] array = new int [number];
// let the user enter the values of the array.
for (int index = 0; index < number; index ++)
{
System.out.print(" Value" + (index+1) + " :");
array[index] = key.nextInt();
}
// Print out the even indexes
System.out.println("/nI am now going to print out the even indexes");
for (int index = 0; index < array.length; index ++)
{
if (array[number+1]%2==0)
System.out.print(array[number]);
}
}
}
You can just change your for loop and get rid of the inner IF...
for( int index = 0; index < array.length; index += 2) {
System.out.println(array[index]);
}
Just absolutely same thing using java 8 Stream API
Integer[] ints = {0,1,2,3,4,5,6,7,8,9};
IntStream.range(0, ints.length).filter(i -> i % 2 == 0).forEach(i -> System.out.println(ints[i]));
I assume this would be sufficient
// For loop to search array
for (int i = 0; i < array.length; i++) {
// If to validate that the index is divisible by 2
if (i % 2 == 0) {
System.out.print(array[i]);
}
}
This is what I did and it works:also I am not printing out index[0] because technically its not even thats why I started the for loop at 2. Your post did help me a lot. I also thank everyone else as well that took the time to post an answer.
import java.util.Scanner;
public class Arrayevenindex
{
public static void main(String[] args)
{
int number; // variable that will represent how many elements the user wants the array to have
Scanner key = new Scanner(System.in);
System.out.println(" How many elements would you like your array to have");
number = key.nextInt();
int [] array = new int [number];
// let the user enter the values of the array.
for ( int index = 0; index < number; index ++)
{
System.out.print(" Value" + (index+1) + " :");
array[index] = key.nextInt();
}
// Print out the even indexes
System.out.println("/nI am now going to print out the even indexes");
for ( int index = 2; index < array.length; index +=2)
{
System.out.print(array[index] + " ");
}
}
}

Finding the minimum and maximum values in a user inputed array (Java)

So I've been tasked with creating a code that creates a predetermined array list for users to input up to over 100 integers with the option of using 0 to signify once their done with their inputs. However, when trying to call for say the minimum value, it just returns a value of 0. How would I properly format it so it compares it to all the value in the user inputted array list? Appreciate any help I can get! I added comments on the side to show which areas I have questions about or where I believe that the error lies.
public static void main(String[] args) {
Scanner TextIO = new Scanner(System.in);
String calc;
double[] numbers2; //An array for storing double values.
int[] numbers; // An array for storing the int values.
int count; // The number of numbers saved in the array.
int num; // One of the numbers input by the user.
int max;
int min;
/* Initialize the summation and counting variables. */
numbers2 = new double[100]; // Space for 100 doubles.
numbers = new int[100]; // Space for 100 ints.
count = 0; // No numbers have been saved
max = Integer.MIN_VALUE; //Properly initialized?
min = Integer.MAX_VALUE; //Properly initialized?
/*Start of min method. */
if (calc.equals("min")){
System.out.println("Enter up to 100 positive integers;
while (true) { // Get the numbers and put them in the array.
System.out.print("-> ");
num = TextIO.nextInt();
if (num <= 0) {
break; } /*Zero marks the end of the input. All
have been inputted. */
else {
numbers[count] = num; // Put num in position count.
count++;
}
for (int i=0; i<numbers.length;i++) { //"For" statement needed here?
if (numbers[i] < min) {
min = numbers[i];}
}
}
System.out.println("Your minimum is : " + min);
}
}
}
Your for loop that finds the minimum should be after the while loop that reads the input, not inside it (since currently it goes over un-initialized elements of the array, so it always finds a 0 as the minimum). If you do that, you should also change the for loop to only iterate over the elements you assigned to the array (indices 0 to count-1), and not the entire array.
Alternately, you can remove the for loop and just put the
if (numbers[count-1] < min) {
min = numbers[count-1];
}
condition inside the while loop.
This will find the minimum in the same loop that reads the input.
Of course, if you do that, you don't need to store the elements in an array at all, so you can further simplify the code.
Here's a possible solution the keeps the array and the for loop :
while (count < numbers.length) { // avoid too many inputs
System.out.print("-> ");
num = TextIO.nextInt();
if (num <= 0) {
break;
} else {
numbers[count] = num;
count++;
}
}
for (int i=0; i<count;i++) {
if (numbers[i] < min) {
min = numbers[i];
}
}

Java Program: finding smallest and largest number of 3 numbers in an array

The code below works fine for the largest value but for the smallest value it is displaying: smallest number is 0 for any 3 values I input. Would greatly appreciate any help.
import java.util.Scanner;
class MyClass{
public static void main(String[] args) {
// declare and create array object
// declare smallest and largest int variables
int[] numbers;
numbers = new int[3];
int smallest = numbers[0], largest = numbers[0];
// create Scanner object
Scanner input = new Scanner(System.in);
// prompt user
System.out.print("Please enter 3 numbers: \n");
// use for loop to obtain user input
for (int counter = 0; counter < numbers.length; counter++) {
numbers[counter] = input.nextInt();
} // end obtaining input
// for loop to find largest and smallest values
for (int i=0 ;i< numbers.length; i++) {
if (numbers[i] < smallest) {
smallest = numbers[i];
} // end finding smallest
if (numbers[i] > largest) {
largest = numbers[i];
} // end finding largest number
}
System.out.println("largest number is "+largest);
System.out.println("smallest number is "+smallest);
}
}
Smallest is always initialized as 0 here: int smallest = numbers[0]. Unless the user enters a value smaller than 0, smallest value will stay 0. Use Integer.MAX_VALUE (int smallest = Integer.MAX_VALUE) instead to ensure that the smallest number will actually be selected.
You're initializing smallest to 0, so if none of the numbers in the array are less than 0, you'll still get 0 as the result. Instead initialize it to Integer.MAX_VALUE, which is the highest value the integer datatype can have.
public static void getMaxMin(int a, int b, int c){
int max=a;
int min=a;
if(b>max){
max=b;
}
if(c>max){
max=c;
}
if(b<min){
min=b;
}
if(c<min){
min=c;
}
System.out.println("min="+min);
System.out.println("max="+max);
}
import java.util.Scanner;
class MyClass {
public static void main(String[] args) {
// declare and create array object
// declare smallest and largest int variables
int[] numbers;
numbers = new int[3];
// create Scanner object
Scanner input = new Scanner(System.in);
// prompt user
System.out.print("Please enter 3 numbers: \n");
// use for loop to obtain user input
for (int counter = 0; counter < numbers.length; counter++) {
numbers[counter] = input.nextInt();
} // end obtaining input
//Use in built Math.min and Math.max to get smallest and largest numbers
System.out.printf("%s: %d%n", "smallest number is ", Math.min(numbers[0], Math.min(numbers[1], numbers[2])));
System.out.printf("%s: %d%n", "largest number is ", Math.max(numbers[0], Math.max(numbers[1], numbers[2])));
}
}

Finding repeats in a 2D array

I have made a program that outputs the number of repeats in a 2D array. The problem is that it outputs the same number twice.
For example: I input the numbers in the 2D array through Scanner: 10 10 9 28 29 9 1 28.
The output I get is:
Number 10 repeats 2 times.
Number 10 repeats 2 times.
Number 9 repeats 2 times.
Number 28 repeats 2 times.
Number 29 repeats 1 times.
Number 9 repeats 2 times.
Number 1 repeats 1 times.
Number 28 repeats 2 times.
I want it so it skips the number if it has already found the number of repeats for it. The output should be:
Number 10 repeats 2 times.
Number 9 repeats 2 times.
Number 28 repeats 2 times.
Number 29 repeats 1 times.
Number 1 repeats 1 times.
Here is my code:
import java.util.Scanner;
public class Repeat
{
static Scanner leopard = new Scanner(System.in);
public static void main(String [] args)
{
final int ROW = 10; //Row size
final int COL = 10; //Column size
int [][] num = new int[ROW][COL];
int size;
//Get input
size = getData(num);
//Find repeat
findRepeats(num, size);
}
public static int getData(int [][] num)
{
int input = 0, actualSize = 0; //Hold input and actualSize of array
System.out.print("Enter positive integers (-999 to stop): ");
//Ask for input
for(int i = 0; i < num.length && input != -999; i++)
{
for(int j = 0; j < num[i].length && input != -999; j++)
{
input = leopard.nextInt();
//Check if end
if(input != -999)
{
num[i][j] = input;
actualSize++;
}
}
}
System.out.println();
return actualSize;
}
public static void findRepeats(int [][] num, int size)
{
int findNum;
int total = 0, row = 0, col = 0;
for(int x = 0; x < size; x++)
{
//Set to number
findNum = num[row][col];
//Loop through whole array to find repeats
for(int i = 0; i < num.length; i++)
{
for(int j = 0; j < num[i].length; j++)
{
if(num[i][j] == findNum)
total++;
}
}
//Cycle array to set next number
if(col < num[0].length-1)
col++;
else
{
row++; //Go to next row if no more columns
col = 0; //Reset column number
}
//Display total repeats
System.out.println("Number " + findNum + " appears " + total + " times.");
total = 0;
}
}
}
I know why it is doing it, but I cannot figure out how to check if the number has already been checked for it to skip that number and go to the next number. I cannot use any classes or code that is not used in the code.
Since you cannot use anything other than this, lets say, basic elements of Java consider this:
Make another temporary 2D array with two columns (or just two separate arrays, personally I prefer this one). On the start of the algorithm the new arrays are empty.
When you take a number (any number) from the source 2D structure, first check if it is present in the first temporary array. If it is, just increment the value (count) in the second temporary array for one (+1). If it is not present in the first tmp array, add it to it and increase the count (+1) in the second at the same index as the newly added number in the first (which should be the last item of the array, basically).
This way you are building pairs of numbers in two arrays. The first array holds all your distinct values found in the 2D array, and the second one the number of appearances of the respective number from the first.
At the and of the algorithm just iterate the both arrays in parallel and you should have your school task finished. I could (and anyone) code this out but we are not really doing you a favor since this is a very typical school assignment.
It's counting the number two times, first time it appears in the code and second time when it appears in the code.
To avoid that keep a system to check if you have already checked for that number. I see you use check int array but you haven't used it anywhere in the code.
Do this,
Put the number in the check list if you have already found the count of it.
int count = 0;
check[count] = findNum;
count++;
Note: You can prefill you array with negative numbers at first in order to avoid for having numbers that user already gave you in input.
Next time in your for loop skip checking that number which you have already found a count for
for(int x = 0; x < size; x++) {
findNum = num[row][col];
if(check.containsNumber(findNUm)) { //sorry there is no such thing as contains for array, write another function here which checks if a number exists in the array
//skip the your code till the end of the first for loop, or in other words then don't run the code inside the for loop at all.
}
}
Frankly speaking I think you have just started to learn coding. Good luck! with that but this code can be improved a lot better. A piece of advice never create a situation where you have to use 3 nested for loops.
I hope that you understood my solution and you know how to do it.
All answers gives you some insight about the problem. I try to stick to your code, and add a little trick of swap. With this code you don't need to check if the number is already outputted or not. I appreciate your comments, structured approach of coding, and ask a question as clear as possible.
public static void findRepeats(int [][] num, int size)
{
int findNum;
int total = 1, row = 0, col = 0;
int [] check = new int[size];
while(row < num.length && col < num[0].length)
{
//Set to number
findNum = num[row][col];
//Cycle array to set next number
if(col < num[0].length-1)
col++;
else
{
row++; //Go to next row if no more columns
col = 0; //Reset column number
}
//Loop through whole array to find repeats
for(int i = row; i < num.length; i++)
{
for(int j = col; j < num[i].length; j++)
{
if(num[i][j] == findNum) {
total++;
//Cycle array to set next number
if(col < num[0].length-1)
col++;
else
{
row++; //Go to next row if no more columns
col = 0; //Reset column number
}
if(row < num.length - 1 && col < num[0].length -1)
num[i][j] = num[row][col];
}
}
}
//Display total repeats
System.out.println("Number " + findNum + " appears " + total + " times.");
total = 1;
}
}
you can use a HashMap to store the result. It Goes like this:
// Create a hash map
HashMap arrayRepeat = new HashMap();
// Put elements to the map
arrayRepeat.put(Number, Repeated);

Categories