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];
}
Related
I am trying to take 10 integers from the user's input and find the minimum and maximum using for loop. But my final print statement just prints the list of numbers entered. I'm lost.
public static void main(String[]args) {
Scanner scan=new Scanner(System.in);
double a = 0;
double max = 0;
double min = 0;
System.out.print("Enter ten floating points: \n");
for(a=0; a <10; a++) {
a=scan.nextDouble();
if(a == 0) {
min=a;
max=a;
}
else if(a < min) {
min=a;
}
else if (a > max){
max=a;
}
}
System.out.println("Minimum value: " +min);
System.out.println("Maximum value: " +max);
}
Issue is in your for loop change it to
for (int x = 0; x < 10; x++) {
there is another issue, you need to change
if(a == 0){
To
if (x == 0) {
Try this
Scanner scan=new Scanner(System.in);
int maximum = Integer.MIN_VALUE;
int minimum = Integer.MAX_VALUE;
for( int i=0; i<10 && scan.hasNextInt(); i++ ) {
int next = scan.nextInt();
maximum = Math.max( next, maximum);
minimum = Math.min( next, minimum);
}
System.out.println("Found maximum :"+maximum+", minimum:"+minimum);
scan.close();
First, we create the scanner.
Next, we set a value for your maximum - since integers can be negative, we can not use 0, but have to use the smallest possible integer.
Same for minimum.
In the for loop, we have to make sure that we terminate the loop after 10 iterations, or if the input stream does not have any more int's.
Next, we use the mathematical function max to find out which number is largest - the previously found maximum, or the next int from the Scanner.
And same for minimum.
Finally, remeber to close the Scanner, to avoid resource leakage.
First your code should not run correctly since you use the same variable a as the counter and as the variable to store user input. You should use two different variable.
Second declare your variable that store the input from user inside the loop, otherwise it may keep the value from the previous loop.
Third your if(a == 0) condition will reset min and max when the user enter the number 0. Which is not what you want.
Finally you should not initialize max/min like that. By defining min as 0, if the user enter only positive number the min will be 0 but the user never entered 0. You instead initialize them at the first entry from user.
This should look like this :
public static void main(String[]args) {
Scanner scan=new Scanner(System.in);
System.out.print("Enter ten floating points: \n");
double tmp = scan.nextDouble(); //read first number from user
double max = tmp; //intialize with the first input
double min = tmp;
for(int i=0; i <9; i++) { //from 0 to 8, 9 numbers since the first has already been read
double a = scan.nextDouble(); //at every loop read a number from the input
if(a < min) {
min=a;
}
//removed else since max and min are independant
if (a > max) {
max=a;
}
}
System.out.println("Minimum value: " +min);
System.out.println("Maximum value: " +max);
}
So, I have a very messy code. The purpose of the code is to find the minimum and maximum values of a set of numbers that the user entered using arrays. The problem is I don't know how to put the Array elements (Elements) into my array (numbersArray). Here's what I have so far :
package com.company;
import java.util.*;
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
public class Main {
public static void main(String[] args) {
/* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */
Scanner elements = new Scanner(System.in);
System.out.println("Enter in number of numbers:");
String num = elements.nextLine();
int numArrayElements = Integer.parseInt(num);
System.out.println("Enter in numbers please: ");
Scanner console = new Scanner(System.in);
String userInput = console.nextLine();
int Elements = Integer.parseInt(userInput);
int [] numbersArray = new int[numArrayElements];
int sum = 0;
for (int i = 0 ; i < numbersArray.length ; i++) {
int temp = numArrayElements.nextInt();
numbersArray[i] = temp;
sum += temp;
}
Arrays.sort(numbersArray);
System.out.println((sum - numbersArray[numbersArray.length-1])
+ " " + (sum - numbersArray[0]));
}
}
How can I make it so that I can put Elements into numbersArray?
Your major problem is the part where you try to read values entered by the user:
for (int i = 0 ; i < numbersArray.length ; i++) {
int temp = numArrayElements.nextInt();
...
}
The variable numArrayElements is of type int, you can't call a method nextInt on it, it does not exist.
The method, however, exists for objects of type Scanner, like your elements variable.
After that your code probably compiles and does something useful. At least you set the array items correctly by using
numbersArray[i] = temp;
I'm not that sure about the min/max part though. I don't get why you need the sum if you sort the array. After sorting you can just take the first (min) and last element (max) given by numbersArray[0] and numbersArray[numbersArray.length - 1].
And I'm not sure why you do the parsing stuff in between, does not seem necessary. Same holds for the second scanner, not needed since you already have one.
Let me show you a cleaner approach.
Scanner scanner = new Scanner(System.in);
// Amount of values
System.out.println("Enter amount of values:");
int amount = scanner.nextInt();
// Read values
System.out.println("Enter " + amount + " values:");
int[] values = new int[amount];
for (int i = 0; i < values.length; i++) {
values[i] = scanner.nextInt();
}
// Compute max and min
...
For the last part you have several options. The most efficient would probably be to remember it already at the moment where you read the values. Your sorting approach works too, but is much more work than needed since you don't need the order of all elements, you only need the min and max element.
Let's first do a manual approach
// Compute max and min
int max = Integer.MIN_VALUE;
int min = Integer.MAX_VALUE;
for (int value : values) {
if (value > max) {
max = value;
}
if (value < min) {
min = value;
}
}
The second approach uses a built-in method which essentially does the same. However, it is less efficient since we will first need to built a Collection on top of the array and then do two iterations instead of only one (one for max, one for min). Also, due to the conversion we need wrapper objects Integer instead of primitive values int.
// Compute max and min
Collection<Integer> valuesAsColl = Arrays.asList(values);
int max = Collections.max(valuesAsColl);
int min = Collections.min(valuesAsColl);
The third approach uses the Java Stream API (since Java 8), looks elegant and does not need to convert stuff to Integer or Collection. But the two iterations instead of one remain.
// Compute max and min
int max = Arrays.stream(values).max();
int min = Arrays.stream(values).min();
I not understand your ask .. however this code for set array size from user and numbers of array by user..
public class JavaApplication2 {
public static int[] numbers() {
Scanner element = new Scanner(System.in);
System.out.print("please insert array long : ");
int count = element.nextInt();
System.out.print("enter numers : ");
element.nextLine(); // throw away the newline.
int [] numbers = new int[count];
Scanner numScanner = new Scanner(element.nextLine());
for (int i = 0; i < count; i++) {
if (numScanner.hasNextInt()) {
numbers[i] = numScanner.nextInt();
} else {
System.out.println("You didn't provide enough numbers");
break;
}
}
return numbers;
}
public static void main(String[] args) {
int[] numbersa = numbers();
System.out.println(Arrays.toString(numbersa));
}
}
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.
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).