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

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)

Related

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);

Modification of Bubblesort program with user input

I have created a program previously using the BubbleSort method that works to sort numbers in a list that already exists, however, I am having difficulty with trying to manipulate this program in order to allow a user to input the list of numbers to be sorted instead. So far I have:
import java.util.Scanner;
public class MedianValue {
public static void main(String[] args) {
//use scanner to input list of numbers to sort
Scanner scan = new Scanner(System.in);
int[] numbers = new int[] {scan.nextInt()};
//nested for loop
//outer loop just iterating
//inner loop going through and flipping
//checking if out of order (if statement)
int counter = 0;
//outer loop: keep doing this until it's sorted
for(int i = 0; i < numbers.length - 1; i = i + 1)
//put in a inner loop number.length times minus one because we don't want to swap the last element
for(counter = 0; counter < numbers.length - 1; counter = counter + 1)
{
if (numbers [counter] > numbers [counter + 1])
{
int temporary = numbers [counter];
numbers [counter] = numbers [counter + 1];
numbers [counter + 1] = temporary;
}
}
for(int i =0; i < numbers.length; i = i + 1)
{
System.out.print(numbers[i] + " ");
}
}
}
But, in this program, instead of sorting the inputted numbers, the program simply prints the first number that is inputted by the user. I am not sure if I need to move where my scanner function is placed, or add on to it within the loop for it to sort all of the numbers as I want it to do. I am lost on where to change the program if that is the case.
That's because int[] numbers = new int[] {scan.nextInt()}; is a single assigment. scan read a single input and assign to number[0].
You actually need to modify your code for scan to read n numbers and store in n-sized numbers.
something like.
int[] numbers = new int[scan.nextInt()];
for( int i = 0; i < numbers.length; i++)
numbers[i] = scan.nextInt();
The code int[] numbers = new int[] {scan.nextInt()}; will always create an array (not a List) of size 1.
Usually in these kinds of assignments you get n + 1 numbers, for example 5 3 6 2 4 1 would mean "I'm going to give you five numbers. Oh here they are: 3 6 2 4 and 1!"
You probably want something like int[] numbers = new int[scan.nextInt()]; - then loop from 0 to numbers.length to fill the array.

Class ArrayIndexOutOfBoundsException - trying to get rid of it

I am writing a program that will take user input for a random number and number of iterations. I am attempting to do a bubble sort on this (for my class I am required to do it with bubble and selection sorts). My initial code did fine till I worked to add in the portion to do iterations and then the selection sort. Now when I run my code, it will stop and give an error noted in the title of my post. The line it stops at is if randomArray[d]>randomArray[d+1] (the last line in the code below).
From what I have researched in my attempts to resolve this, it says the error is usually thrown when the array has been accessed by illegal index... or the index is negative or greater than the size of the array. I have attempted a few different things to fix this, but at the moment I am at a wall. If anyone can provide some direction, I would greatly appreciate it!
Thanks
Scanner input = new Scanner (System.in);
System.out.println("Enter a number please: ");
int n = input.nextInt();
//Get user input for number if iterations
System.out.println("Enter a number of iterations please: ");
int numIfor = input.nextInt();
//create array of random numbers
int[] randomArray = new int[n];
Random bubbleRandom = new Random();
//fill in the array of random numbers
for(int i=0; i < n; i++) {
randomArray[i] = bubbleRandom.nextInt(100);
}
//Printing the array before the sort
System.out.println("The numbers before the Bubble Sort: ");
for(int i=0; i < n; i++) {
System.out.print(randomArray[i] + " ");
}
System.out.println();
//Printing the array out after the Bubble Sort
int bubble = 0;
int sort = 0;
long startTime = System.currentTimeMillis();
for (int c=0; c < (numIfor - 1); c++)
{
for (int d=0; d < numIfor - c -1; d++)
{
if (randomArray[d]>randomArray[d+1])
{
bubble = randomArray[d];
randomArray[d] = randomArray[d+1];
randomArray[d+1] = bubble;
sort++;
}
}
}
long endTime = System.currentTimeMillis();
long runningTime = endTime-startTime;
System.out.println("The total number of iterations is: " + numIfor);
System.out.println("The total count of numbers sorted is: " + sort);
System.out.println("The total time elapsed was: " + runningTime);
System.out.println("The numbers after the Bubble Sort: ");
for(int i=0; i < n; i++){
System.out.print(randomArray[i] + " ");
}
}
}
What is probably happening is that d+1 is becoming larger than the last position of the array. You can make sure it only goes up to the end of the array by changing the last for loop as such:
The problem here is that you are looping to numIfor, which is a completely independent value from the length of the array (n). This means that if the user enters a numIfor and n, such that numIfor > n, then your code is bound to throw the exception.
The solution to this is using the actual length of the array as the limiter value instead, as such:
for (int c=0; c < randomArray.length-1; c++)
{
for (int d=0; d < randomArray.length-c-1; d++)
{
if (randomArray[d]>randomArray[d+1])
This is assuming that you want d to go through all the values of the array. But the real takeaway here is that you should always try to loop to less than the length of the array (the -1 is there because you are checking for array[d+1]). This works best if you are trying to reach all the values in the array because it guarantees that you don't go out of bounds.

Reversing user input array in Java

I'm trying to shift the user number input from right to left. It seems to be working except for not registering the first number. I think because for the reverse portion I have count is 1. I've tried using 0 and vice verse, but it results in an error. Any ideas on how to shift the user numbers?
The desired output is the reverse of what the user inputs. Example: User inputs 3 numbers. 3.0 2.0 1.0. Reverse 1.0. 2.0. 3.0.
// import Scanner
import java.util.Scanner;
public class Arrays {
public static void main (String [] args){
int count=0;
//introduce Scanner
Scanner input = new Scanner(System.in);
//printout question asking for user input and use count as input variable
System.out.println("Please input the size of array");
count=input.nextInt();
//create array and connect count to it
double[] numbers = new double [count];
System.out.println("Please input "+ numbers.length+ " double numbers");
//create for loop for original number order
for ( count=0; count<numbers.length; count++){
numbers[count] = input.nextDouble();
System.out.print( +numbers[count] + " ");
}
//print out the reverse order
System.out.print("\n After Reverse Order " );
//create for loop for reversed number order
for (count = 1; count< numbers.length; count++){
numbers[count-1]=numbers[count];
System.out.println ( "\n"+ numbers[count] );
}
}
}
If you want to reverse the order of elements, that's REVERSE ORDER not SHIFT. "Shift" correctly would shift them all one to the right or left, either dropping the end element or or (possibly) rotating it round to the other end.
So first thing is, to know what you're actually talking about.
Reversing the order of integers in an array:
int i = 0;
int j = numbers.length - 1; // corresponding index at opposite end of array.
// stop when half the array has been swapped.. with the other half.
while (i < j) {
// swap between ends.
int swap = numbers[i];
numbers[i] = numbers[j];
numbers[j] = swap;
// advance indices.
i++; j--;
}
Try this:
Double[] numbers = new Double[count];
...
Collections.reverse(Arrays.asList(numbers));

errors in java - finding maximum values in an ArrayList

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).

Categories

Resources