I am creating a program that asks the user for ten numbers, then outputs the smallest and largest number. This 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 (i < smallest) {
smallest = i;
} // end finding smallest
else if (i > largest) {
largest = 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);
} // end main
} // end ArrayTester
The problem I am having is when the numbers output, it's giving me 0 as the smallest and 9 as the largest. I know this is because of the 10 number array but how would it be fixed to show the smallest integer and largest integer?
numbers = new int[10];
The above statement initialises the array with all 0s, since you are assigning numbers[0] to smallest, it will always be 0.
Also, another way of achieveing this would be by using Java 8's stream, e.g.:
int[] array = new int[] {1,2,3,10,0};
IntSummaryStatistics summaryStatistics = Arrays.stream(array).summaryStatistics();
System.out.println(summaryStatistics.getMax());
System.out.println(summaryStatistics.getMin());
Put this line:
int smallest = numbers[0], largest = numbers[0];
Below this line:
for (int counter = 0; counter < numbers.length; counter++) {
numbers[counter] = input.nextInt();
} // end obtaining input
You're initializing "smallest" to 0, because your array doesn't have any values yet. Unless the user puts in a negative number, smallest will always be zero.
Related
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)
I needed an array that takes integers from a user until '0' is entered; then it prints average, max and min. I wrote an array with 700 elements and it breaks. When I input 0 everything works well. The problem is when I input 0 it takes 0 as an element. I solved that somehow so it can calculate the average correctly but it still takes some 0 from somewhere. For example, I input 8 and then 3 and then 0, and the output is the average is 4.000000, the biggest one is 5, the smallest one is 0, but the smallest one should be 3.
I guess it's because the remaining 697 elements are considered as 0.
I found a lot of answers for this problem but I want to solve it without copying the array or creating a new one. Is there anything that I can do to fix this without adding an array or another for loop or something? Like a line that means 'when the 0 is entered remove all remaining elements and don't use them for anything'?
import java.util.Scanner;
import java.util.stream.IntStream;
public class PlayingWithNumbers2 {
private static Scanner input;
public static void main(String[] args) {
input = new Scanner(System.in);
int[] array = new int[700];
System.out.println("Enter numbers enter 0 to end");
int i;
int max = array[0];
int min = array[0];
int a = array[0];
for (i = 0; i < array.length; i++) {
a=input.nextInt();
if(a==0){
break;
}
array[i] = a;
if(array[i]>max)
max = array[i];
else if(array[i]<min)
min = array[i];
}
double sum = IntStream.of(array).sum();
double Ave = sum/i;
System.out.printf(" The Average is %f \n the biggest one is %d \n the smallest one is %d", Ave, max, min);`
}
}
The problem with the min/max is both are initialized to array[0] which means both are initialized to '0' and so the min check will always keep it at 0 as it is below anything you enter. You also need to remove the else condition. Try this
int max = Integer.MIN_VALUE;
int min = Integer.MAX_VALUE;
then inside the loop change the checks to be
if(array[i]>max)
max = array[i];
if(array[i]<min)
min = array[i];
You can use range():
double sum = IntStream.of(array).range(0, i).sum();
double Ave = sum/(i-1);
In this way, you'll be counting only numbers that are truly entered by the user and leave 'fake' 0 out of your sum.
I am trying to recursively find the largest element in an array. The user has to input the number of elements that the array will have. My error is that if that the list does not have an element which is larger than the number of elements in the list, the output of the largest number will be the number of elements in the list. eg: array of 5 integers containing {1 1 1 2 3}. the answer will be 5 and not 3.
import java.util.*;
public class test7 {
public static int findLargest(int[] a, int max) {
int i=0, j=0, tempmax=0;
if (a.length == 1) return a[0]>max ? a[0]:max;
else if(max < a[i]){
max = a[i];
int[] tempArr = new int[a.length -1];
for (i=1; i<a.length; i++){
tempArr[j] = a[i];
j++;
}
tempmax = findLargest(tempArr, max);
return tempmax;
}
else{
int[] tempArr = new int[a.length -1];
for (i=1; i<a.length; i++){
tempArr[j] = a[i];
j++;
}
tempmax = findLargest(tempArr, max);
return tempmax;
}
}
public static void main(String[] args) {
int[] values = new int[100];
Scanner scan = new Scanner(System.in);
System.out.println("Enter the number of elements in your list: ");
int x = scan.nextInt();
if(x>1 || x<100){
for (int i=0; i<=(x-1); i++){
System.out.print("Enter your number: ");
System.out.println();
values[i] = scan.nextInt();
}
System.out.println();
System.out.println("The largest number is: "+findLargest(values, x));
}
else System.out.println("The maximum number of elements must be less than 100");
}
}
You call your method with:
System.out.println("The largest number is: "+findLargest(values, x))
This tells it to assume the largest number is x and try to find anything in the list that is greater than that. Of course, this produces the exact problem you described.
In general, when finding a maximum number, you want to initialize your candidate to the lowest number possible, or to the first number in your array.
If you initialize to the lowest number possible (Integer.MIN_VALUE) then as soon as you start your algorithm, the first number will definitely be bigger than it and will be chosen as the next candidate for maximum.
If you initialize to the first item in your array, then if that number is the highest, all well and good. If it is not, then when you encounter the next higher number, it will become the candidate, and all is good.
Which one you choose is up to you (and depends also on whether an empty array is possible), but the thing to remember is never to select an initial candidate that might be greater than all the elements in the array.
Try this working example:
public static void main(String[] args)
{
int[] numbers = {2, 5134, 333, 123, 8466};
int largest = numbers[0];
for(int i = 1;i<numbers.length;i++)
{
largest = Math.max(largest, numbers[i]);
}
System.out.println("Largest number: "+largest);
}
As a method that would look like this:
public static int max(int first, int... more)
{
for(int element:more)
{
first = Math.max(first, element);
}
return first;
}
You can then call it using something like max(1,23,564,234,543);
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.
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).