Removing all the zeros from an array using scanner - java

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.

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

Find a maximum and minimum value using for loop

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

Input inside Arrays (java)?

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

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.

Categories

Resources