errors in java - finding maximum values in an ArrayList - java

Following is the program I wrote as an answer for the question -
"Now use ArrayList and the Integer wrapper class to store the values and initialize the elements by reading input from console using Scanner class.Extend the program to identify the n maximum values in the ArrayList."
import java.util.ArrayList;
import java.util.Scanner;
public class ArraylistInput {
/**
* #param args
*/
public static void main(String[] args) {
ArrayList<Integer> val = new ArrayList<Integer>();
Scanner in = new Scanner(System.in);
System.out.println("Enter the length of you Array List ");
int nos = in.nextInt();
// Recorrd the input numbers
for (int i = 0 ; i < nos; i++)
{
System.out.println("Enter values for the ArrayList ");
int Input = in.nextInt();
val.add(Input);
}
// Display the arraylist
for (int j = 0; j < nos; j++)
{
int x = val.get(j);
System.out.println("Index " + (j+1) + ": " + x);
}
System.out.println("How meny maximmum values do you want? ");
int max =0; // initial max value
int nmax = in.nextInt(); // number of maximum values
int length = val.size(); // size of the arraylist
// finding the maximum values in ascending order without sorting
for (int h = 1; h <= nmax ; h++)
{
for (int k=0;k < length; k++)
{
if (val.get (k) > max)
{
max = val.get(k);
}
}
System.out.println ("maximmum = " + max);
int z = val.indexOf(max); // removing the higest value after printing
val.remove(z);
}
}
}
Output and Error:
Enter the length of you Array List
3
Enter values for the ArrayList
12
Enter values for the ArrayList
45
Enter values for the ArrayList
8
Index 1: 12 Index 2: 45 Index 3: 8
How meny maximmum values do you want?
2
maximmum = 45
Exception in thread "main" maximmum = 45
java.lang.ArrayIndexOutOfBoundsException: -1 at
java.util.ArrayList.elementData(Unknown Source) at
java.util.ArrayList.remove(Unknown Source) at
ArraylistInput.main(ArraylistInput.java:46)

I would do the following:
Collections.sort(myList, Collections.reverseOrder());
List<Integer> maxn = myList.subList(0, n);
System.out.printf("The maximum %d values are: %s%n", n, maxn);
maxn.clear(); //This clears the sublist and removes its elements from the source list
That would give you a list with the maximun n elements in your list.

You only have a single ArrayList you don't need the nested for loop to find the maximum:
int max = Integer.MIN_VALUE;
for(int i = 0; i < list.size(); i++)
{
current = list.get(i);
if(current > max)
max = current;
}
The nested for loop when you are searching for the maximum tries to access a value in your list that doesn't exist, which is why you are receiving this error.

Your max is never getting assigned and then you are trying to remove a non-existing element from the arraylist. Set max to some value that cannot occur in the list and then check whether it ever got assigned in the loop.

When you remove an element from the list with:
val.remove(z);
You change the size of the list but you don't update your length variable. This causes you to try to access indices beyond the size of the array, resulting in a java.lang.ArrayIndexOutOfBoundsException.
Also, consider saving both the index of the max value and the max value itself. Then, when you go to remove the value, you can use ArrayList.remove() directly without searching the whole list again for the max index (which is what ArrayList.indexOf() will do).

Related

Getting 0 for minimum value but the maximum value is okay

I am trying to input an array using a scanner. That part is already done. Now, I am tasked to get the maximum and minimum numbers from my input. I was able to get the maximum but with the minimum, it is returning 0.
Is there a misplacement of syntax perhaps?
import java.util.Scanner;
public class App {
public static void main(String[] args) {
int in;
Scanner sc = new Scanner(System.in);
System.out.print("Enter the number of elements you want to store: ");
in=sc.nextInt();
int array[] = new int[in];
int min = array[0];
int max = array[0];
for (int i=0; i < in; i++){
System.out.print("Input number "+(i+1)+" :");
array[i]=sc.nextInt();
if(array[i]>max){
max=array[i];
}
else if (array[i]<min){
min=array[i];
}
}
sc.close();
System.out.print(" The inputed array is ");
for (int i=0; i < in; i++){
System.out.print(array[i]+" ");
}
System.out.println("\n --------------------");
System.out.println("The highest number is: "+max);
System.out.println("The lowest number is: "+ min);
}
}
(also if you can, can y'all tell me how to get the index of the minimun and maximum value and print it?)
I tried different if and else if methods. I also tried nesting but I am getting the same outcome.
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Scanner;
public class App {
public static void main(String[] args) {
int in;
List<Integer> elements = new ArrayList<>();
Scanner sc = new Scanner(System.in);
System.out.print("Enter the number of elements you want to store: ");
in=sc.nextInt();
for (int i=0; i < in; i++){
System.out.print("Input number "+(i+1)+" :");
elements.add(sc.nextInt());
}
sc.close();
List<Integer> unsorted = new ArrayList<>(elements);
Collections.sort(elements);
int max = elements.get(elements.size()-1);
int min = elements.get(0);
System.out.println("\n --------------------");
System.out.println("The highest number is: "+max);
System.out.println("The lowest number is: "+ min);
System.out.println("Index of Min Value is : "+unsorted.indexOf(min));
System.out.println("Index of Max Value is : "+unsorted.indexOf(max));
}
}
When you declare an initialize your int array[]:
int array[] = new int[in];
you essentially are filling each array element with 0 by default. Then, when you declare and initialize the min and max variables with array[0] it would be the same as declaring:
int min = 0;
int max = 0;
The max variable is at a relatively low value which is good unless the User enters all signed (negative) integer values to make up the array elements in which case none of those entry values will ever max over 0 which means at the end, max will be 0 which is also wrong.
The same theory applies to the min variable. Since the min variable already holds a low value of 0 (initialized as such), the only way an element value within the array[] Array will be lower is if the array actually contained a signed (negative) value. If it doesn't the the already held value in min will remain to be the lowest value...which as you know will be in most cases wrong.
The thing to do in this particular use-case would be to initialize the min variable with a value which would be the largest a int data type can hold:
int min = Integer.MAX_VALUE;
You would be pretty much guaranteed that a value within the int[] array will never exceed Integer.MAX_VALUE and that if there is a element within the array that is lower, min will end up getting updated to that value.
The same should be applied to the initialization of the max variable except with the lowest possible int data type value:
int max = Integer.MIN_VALUE;
I think at this point you can understand why. ;)
So, all in all, simply change:
int min = array[0];
int max = array[0];
to this instead:
int min = Integer.MAX_VALUE;
int max = Integer.MIN_VALUE;
and all should be fine.
On A Side:
In a real world application where a User is expected to fill in values for an Array, there is no way of knowing what the User (like your instructor) may be entering to fill the elements of that array unless you code specifically to ensure a particular value range. By doing what is described above eliminates any worry of that unless the User supplies a value greater than what an int data type can accept in which case an exception would occur and the application will crash.
You are initializing min even before taking inputs. That's why the min value is always 0 because the default initial value of int array is 0. So, the else if (array[i]<min) condition is never met because no non-negative integer can be smaller than 0.
You can try adding this in your for loop AFTER you take inputs:
if(i==0){
min = array[0];
max = array[0];
}
You can also use type Integer (instead of int), as they can be initialized by null
Integer max = null;
Integer min = null;
In your loop:
if(max == null || max < array[i]) {
max = array[i];
}
if(min == null || min > array[i]) {
min = array[i];
}

Having problems with writing a method to find the index of the biggest integer in my ArrayList

I am having problems in creating a method that will find the index of the biggest integer.
I have tried creating plenty of methods but I was only recently introduced to finding the index of a value in a list, and I still am unable to find the best, let alone a working way. By index I assumed that it is the position of the value within the list given (please correct me if I am wrong).
My Current Code:
import java.util.ArrayList;
import java.util.Scanner;
public class FindBiggest2 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
ArrayList<Integer> integerList = new ArrayList<Integer>();
System.out.println("Enter any amount integers (0 to stop): ");
int integer = input.nextInt();
while(integer != 0) {
integerList.add(integer);
integer = input.nextInt();
}
input.close();
if(integerList.size() == 0) {
System.out.println("list is empty");
return;
}
System.out.println("\nThe integers entered are: ");
// displaying ids
for(int i=0; i<integerList.size(); i++)
System.out.print(integerList.get(i)+" ");
System.out.println();
// finding biggest id
int bInt = integerList.get(0); // initializing bid id with first element
for(int i=1; i<integerList.size(); i++)
if(bInt < integerList.get(i))
bInt = integerList.get(i);
System.out.println("The biggest integer in the array is: "+ bInt);
}
}
My current output (Example):
Enter any amount of integers (0 to stop):
1
2
3
4
5
6
0
The integers entered are:
1 2 3 4 5 6
The biggest integer in the array is: 6
These are my requirements of my output:
The output of the program should firstly display all integers, and then
indicate the biggest integer among them as well as the index of the biggest integer in the 1D
array.
So your index in this loop:
int bInt = integerList.get(0); // initializing bid id with first element
for(int i=1; i<integerList.size(); i++) // i = index
if(bInt < integerList.get(i))
bInt = integerList.get(i);
would be i. Along with int bInt, you'll want an int maxIntegerIndex to hold that value until the for loop concludes.
One stylistic choice I'd suggest that you can feel free to ignore is using curly braces to explicitly declare what code is running in a loop / if statement. This will prevent issues later on in code reading and execution where it appears code should run but isn't. It'll save you a lot of time tracking down seemingly broken code down the road and costs almost nothing.
I am having problems in creating a method that will find the index of
the biggest integer.
In the same way that you are storing the largest value, also store the value of "i" in a separate variable:
// finding biggest id AND the index where it was found
int index = 0;
int bInt = integerList.get(0); // initializing bid id with first element
for(int i=1; i<integerList.size(); i++) {
if(bInt < integerList.get(i)) {
bInt = integerList.get(i);
index = i;
}
}
System.out.println("The biggest integer in the array is: "+ bInt);
System.out.println("It was found at Index: "+ index);

How to traverse through a one dimensional array in java [duplicate]

This question already has answers here:
Finding the minimum value of int numbers in an array (Java)
(10 answers)
Closed 5 years ago.
This is my first question on this site.
Anyways i'm making a program that will prompt the user for how many grades to enter. Then prompt the user to enter grades between 0 and 100 and store them in a array. Finally traverse the array to find the highest grade entered and display it to the user.
The problem i'm encountering is i have no clue on how to traverse through an array to compare two indexs in a array.
import java.util.*;
public class HighestGrade {
public static void main(String[] args) {
//Declare and Initialize Arrays and Scanner
Scanner scan = new Scanner(System.in);
int num = 0;
int[] array1;
int highestgrade = 0;
//Prompt user on how many grades they want to enter
System.out.print("How many grades do you want to enter: ");
num = scan.nextInt();
array1 = new int[num];
for(int i = 0; i < array1.length; i++){
System.out.print("Enter grade out of 100: ");
array1[i] = scan.nextInt();
}
//Traverse the array to find the highest grade entered
for (int i = 0; array1[0] < array1[i]; i++){
System.out.print("Higher");
}
//Display the results to the user
System.out.print("The highest grade is " + highestgrade + ".");
//Close scanner
scan.close();
}
}
To traverse through an array you can use a loop. For loop or while loop or do while loop.
To traverse through an array and keep track of the highest value you can maintain a variable and update it after each iteration if a value larger than that is encountered.
Speaking in terms of code..
int max = arr[0];
for ( int i = 0; i < arr.length; i++) {
if (arr[i] > max)
max = arr[i];
}
System.out.println("Largest is : "+max);
Hope this helps..!!
Also you can use Recursion to traverse an array. But it is not recommended as it will lead to stack related issues..
Another approach to get the highest value without traversing can be seen like this..
Step 1 : Sort the array in ascending order
Step 2 : Highest value will be at the end of the array, Use it as highest value
In codes..
Arrays.sort(arr);
System.out.println("Highest Value is : "+arr[arr.length - 1]);
To traverse the array you need to change your for loop like this:
for (int i = 0; i < array1.length; i++){
// do something with array1[i]
}
Is actually what you already did to fill it. Just do the same to use its values. But there is an alternative to get the highest value, you can use Arrays.sort:
Arrays.sort(array1); // sort values in ascending order.
System.out.println(array1[array1.length-1]); // get the element in the last position (the greatest)

How to find greatest number

How to compute the greatest number and display it?
import java.util.Scanner;
public class GreatestNumber {
public static void main(String[] args) {
int [] num = new int [10];
int counter;
int max = 0;
Scanner read = new Scanner(System.in);
for (int i=0; i<num.length; i++)
{
System.out.print("Enter StaffID to be edited:");
num[i]=read.nextInt();
}
}
}
You probably want to compare the numbers as you're reading them. Also, using 0 as a starting value for max will not print out the results you want if all input values are negative. Use Integer.MIN_VALUE instead:
int [] num = new int [10];
int counter;
int max = Integer.MIN_VALUE; // <-- initial value
Scanner read = new Scanner(System.in);
for (int i = 0; i < num.length; i++)
{
System.out.print("Enter StaffID to be edited:");
num[i] = read.nextInt();
if (num[i] > max)
{
max = num[i];
}
}
System.out.print("Max number is:");
System.out.print(max);
Beside the solution provided by other users, you can make a List from the Array and then use an already existing method that finds the maximum value in the list.
List list = Arrays.asList(ArrayUtils.toObject(num));
System.out.println(Collections.max(list)); //Will print the maximum value
This is how you can do it:
Since you are after the largest number, create an integer which has a very small value.
Iterate over the elements of your array. If the element you are currently looking at is larger than the current largest element (initialized in step 1), then update the value of the largest element.
keep track of the current max and update it if you find a higher number, ie
if (num[i] > max)
max = num[i];
Set a running variable max to Integer.MIN_VALUE. Compare it in a loop with every element in the array, and if the array element is bigger, copy its value to max. In the end you have the biggest element in max.

This code keeps on returning 0 instead of increasing in size?

What I am trying to do is:
Prompt the user for a list size (e.g., N = 10,000). Create an ArrayList of the Integers from 1 to N, in random order.
This is what I have so far, but the list just returns the number 0 n times
System.out.print("Please enter a list size: ");
Scanner ST = new Scanner(System.in);
int n= ST.nextInt();
List<Integer> myList = new ArrayList<Integer>(n);
for ( int i = 1; i<(n+1); i++){
int k = 0;
k = k + 1;
myList.add(k);
}
Yes, because you're declaring k inside the loop. Just move
int k = 0;
to before the loop. Currently the "newly declared" variable will be assigned the value of 0 on the first line of each iteration of the loop; it will then be incremented to 1 on the next line. Then that value (1) will be boxed and the return value Integer.valueOf(1) will be added to the list. Then we go round again...
An alternative is to just use the loop index - potentially changing the loop to a rather more idiomatic style at the same time:
for (int i = 0; i < n; i++) {
myList.add(i + 1);
}

Categories

Resources