User input and array analysis - java

I have a CountInRange Java program that accepts an integer array, also asks the user to input the minimum and maximum value. Then outputs the count of elements from the array that fall between the minimum and maximum values.
Why is it not working?
int [] num ={1, 21, 34, -54, 12, 15, 35};
int count = 0;
int i = 0;
int j = 0;
int min;
int max;
System.out.println("Enter minimum: ");
min = input.nextInt();
System.out.println("Enter maximum: ");
max = input.nextInt();
for (i = 0; i < num.length; i++){
for (j = 0; j < num.length; j++) {
if (num[i] >= min || num[i] <= max) {
count++;
}
}
}
System.out.println("There are "+count+" elements whose values fall between the maximum and the minimum value");
}

The inner for loop is not needed in the least and you should get rid of it.
Also you need to make the conditional and instead of or so it should look something like this:
for (i = 0; i < num.length; i++){
if (num[i] >= min && num[i] <= max) { //AND INSTEAD OF OR
count++;
}
}
You were testing if the number is >= min OR num <= max which means if one of these is true it will return true so if your limit was min = 4 and max = 5 and num = 12 it would return true because 12 >= 4.

Related

print max num in an array in java

import java.util.Scanner;
public class maxnuminarray {
public static void main(String[] args) {
int temp;
System.out.print("please insert the size for array:");
Scanner input = new Scanner(System.in);
int size = input.nextInt();
int[] nums = new int[size];
for (int i = 0; i < size; i++) {
System.out.print("please insert your desired nums:");
nums[i] = input.nextInt();
}
for (int i = 1; i < size; i++)
for (int j = 0; j < size - i; j++)
if (nums[i] > nums[i + 1]) {
temp = nums[i];
nums[i] = nums[i + 1];
nums[i + 1] = temp;
}
System.out.print(nums[size - 1]);
}
}
Though it gets all the values for the array, it still doesn't print the max number which is the last num in the array.
The error I get for size=5:
Exception in thread "main": java.lang.ArrayIndexOutOfBoundsException: Index 5 out of bounds for length 5
at maxnuminarray.main(maxnuminarray.java:15)
Once you read in the values, iterate over the array like this.
int max = Integer.MIN_VALUE;
for (int n : nums) {
max = Math.max(max, n);
}
You're trying to get a value with an index that doesn't exist. For instance, at if (nums[i] > nums[i + 1]). Let's say you have 3 numbers in total, your array size will be 3, but your index starts at 0.
Index 0
Index 1
Index 2
5
10
21
If you try to get i + 1 when i = 2 you get an error since i = 3 does not exist.
Also, if you're trying to get the largest number out of the array, you only need to go through the array once.
int[] nums = new int[]{1, 10, 3};
int max = nums[0];
for (int i = 1; i < nums.length; i++)
if (max < nums[i])
max = nums[i];
Or you can use Collections with the Integer[] array.
int max = Collections.max(Arrays.asList(num));
If you are just looking to find the maximum in the array, #Nouredine's code should do the trick.
Your code is comparing consecutive numbers one by one through the array, and swapping them in a bubble sort kind of way.
But if you are really looking to move the maximum in the array to the last position in the array, you can use this piece of code.
The issue in your code is you are accessing 5th index in an array of size 5, where only 0,1,2,3,4 are allowed.
for (int i = 1; i < size; i++)
if (nums[i - 1] > nums[i]) {
temp = nums[i - 1];
nums[i - 1] = nums[i];
nums[i] = temp;
}
}
import java.util.Scanner;
public class maxnuminarray {
public static void main(String[] args) {
int temp;
System.out.print("please insert the size for array:");
Scanner input = new Scanner(System.in);
int size = input.nextInt();
int[] nums = new int[size];
for (int i = 0; i < size; i++) {
System.out.print("please insert your desired nums:");
nums[i] = input.nextInt();
}
int max = nums[0];
for (int i = 1; i < size; i++)
if(max < nums[i])
max = nums[i];
}
System.out.println("Max " + max);
}

Analasys program max and min and mode and graphing histogram

Hi in my program I want to display the average number, largest number, lowest number, and the mode in the array. So far only my average works and my methods for min and max both = the first number I enter. For example if I say I want to enter 3 numbers and I put 12, 15,and 6. The min and max will both output 12 since it's the first number entered and that's wrong so please help. Here's my code.
int amount;
System.out.println(" Enter the amount of numbers you would like to enter: ");
amount = scan.nextInt();
int [] arr = new int [amount];
int outcome = 1;
for (int i = 0; i < arr.length; i++){
System.out.println("Enter a number 1 through 50");
outcome = scan.nextInt();
arr [i] = outcome;
}
System.out.println(" ");
System.out.println( " The average is" );
System.out.println(average(arr));
System.out.println(" ");
System.out.println( " The lowest value in the array is " );
System.out.println(min(arr));
System.out.println(" ");
System.out.println( " The largest value in the array is " );
System.out.println(max(arr));
System.out.println(" ");
}
public static double average ( int [] arr) {
double sum = 0;
int value = arr.length;
for ( int i = 0; i < arr.length; i++){
sum += arr [i];
}
sum = sum / value;
return sum;
}
public static int min (int [] arr) {
int shortest = 0;
int smallest = 100;
int length = arr.length;
for ( int i = 0; i < arr.length; i ++ ) {
if ( length < smallest)
shortest += arr[i];
smallest = arr.length;
}
return shortest;
}
public static int max (int [] arr) {
int largest = 0;
int biggest = 0;
int length = arr.length;
for ( int i = 0; i < arr.length; i ++ ) {
if ( length > largest)
biggest += arr[i];
largest = arr.length;
}
return biggest;
}
}
This would be pretty straightforward. The reason both your min and max methods return 12 is because you set both largest and smallest to arr.length and thus immediately stop the for-loop after only one run. Also, there are far easier implementations for this kind of problem. Try doing something along these lines:
public int getMax(int[] arr)
{
int max = arr[0]; //To have a baseline
for(int i = 1; i < arr.length; i++)
{
if(arr[i] > max)
{
max = arr[i];
}
}
return max;
}
public int getMin(int[] arr)
{
int min = arr[0]; //To have a baseline
for(int i = 1; i < arr.length; i++)
{
if(arr[i] < min)
{
min = arr[i];
}
}
return min;
}
This is both far more readable and easier to execute. Just ask if you have any questions :-)

Java Application of Arrays and For-loop

Here's the question:
Write a program that that reads ten integers into an array and
computes the sum of the array of values, except for the largest one.
(Hint: Find the difference between the sum and the largest value of the
array)
And this is the given sample that you have to achieve:
Please input 10 integers: 3 4 1 9 2 10 8 6 7 5
Sum without the max: 45
The program beneath is my personal attempt:
import java.util.Scanner;
public class SumWithoutMax {
public static void main(String[] args) {
Scanner in = new Scanner (System.in);
System.out.print("Please input 10 integers: ");
int [] x = new int [10];
for (int i = 0; i < x.length; i++) {
x[i] = in.nextInt();
}
int max = x[0];
int sum = 0-max;
for (int i = 0; i < x.length; i++) {
if(x[i] > max) {
max = x[i];
}
}
for (int i = 0; i < x.length; i++) {
sum = sum + x[i];
}
System.out.println("Sum without the max: " +sum);
}
}
And the result of my attempt is just like this:
Please input 10 integers: 3 4 1 9 2 10 8 6 7 5
Sum without the max: 52
What's wrong with the program actually? Can somebody help me find it out and teach me how to solve it? Thanks:)
Problem with your code is you are subtrating x[0] value (which assume max at initial).
Even You can achive the with single for-loop.
int max = x[0];
int sum = 0;
for (int i = 0; i < x.length; i++) {
if(x[i] > max) {
max = x[i];
}
sum = sum + x[i];
}
sum -=max;
You are subtracting the maximum before you know it. Move int sum = 0-max; after the loop that seeks it.
The first sum=0-max; is wrong because max is not known yet. You need to do it after you find the max.
for (int i = 0; i < x.length; i++) {
sum = sum + x[i];
}
sum -= max;
int sum = -max;
When loop find the maximum number.
Move this line:
int sum = -max;
after the loop that finds the max.
import java.util.Scanner;
public class SumWithoutMax {
public static void main(String[] args) {
Scanner in = new Scanner (System.in);
System.out.print("Please input 10 integers: ");
int [] x = new int [10];
for (int i = 0; i < x.length; i++) {
x[i] = in.nextInt();
}
int max = x[0];
int sum = 0;
for (int i = 0; i < x.length; i++) {
if(x[i] > max) {
max = x[i];
}
}
for (int i = 0; i < x.length; i++) {
sum = sum + x[i];
}
sum = sum - max;
System.out.println("Sum without the max: " +sum);
}
}
A possible answer in JAVA 8 :
Integer sum = Arrays.asList(3,4,1,9,2,10,8,6,7,5).stream().sorted(Comparator.reverseOrder()).skip(1).reduce(
0,(a, b) -> a + b);

Java array minimum element within for-loop

OK, I have been at it for a long time now. I have looked after similar problems here in stack-overflow and I still can't make it work. I need to find the maximum values within an array and minimum values. Trying to find the minimum is the problem. I have literately tried everything from writing separate methods and so on and still the output in 0. Here is what I have tried:
import java.util.Scanner;
class ArrayMin {
public static void main(String args[]) {
#SuppressWarnings("resource")
Scanner scanner = new Scanner(System.in);
int a[] = new int[10];
int max = a[0];
int min = a[0];
System.out.println("Enter elements of array :");
for (int i = 0; i < 10; i++) {
a[i] = scanner.nextInt();
if (i == 9)
break;
}
for (int i = 1; i < a.length; i++) {
if (a[i] > max)
max = a[i];
else if (a[i] < min)
min = a[i];
}
System.out.println("Result is max is :" + (max)); //if I input 1-10, output is 10
System.out.println("Result is min is :" + (min)); //whatever number I input the output is always 0
}
}
When you declare your array, it's initialized to all zeroes. Then you assign the min to your first element, which is zero. Presumably all values are >= to 0 once they're assigned, so the min is still zero, but the max is correct.
Establish your max and min after the for loop where you assign input values to the array.
for (int i = 0; i < 10; i++) {
a[i] = scanner.nextInt();
if (i == 9)
break;
}
// Moved HERE.
int max = a[0];
int min = a[0];
Replace this.
int max = Integer.MIN_VALUE;
int min = Integer.MAX_VALUE;
...
for (int i = 0; i < a.length; i++) {
if (a[i] > max)
max = a[i];
if (a[i] < min)
min = a[i];
}
...

Validate a user's integer input?

I need to ensure that a user enters a number between 10 and 100. If they do not, I want them to enter a new number. In between the asterisks is where my problem is (I think). Thanks in advance.
import java.util.Scanner;
public class Duplicate
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
int[] array = new int[5];
System.out.println("Enter 5 integers between 10 and 100 (inclusive):");
for (int i = 0; i < array.length; i++)
****if ((input.nextInt() <= 100) || (input.nextInt() >= 10))
{
array[i] = input.nextInt();
}
****else { System.out.print("Please enter a number greater than 9 and less than 101."); }
for (int i = 0; i < array.length; i++)
System.out.print(array[i] + ", ");
System.out.println();
System.out.println("Unique values are: ");
for (int i = 0; i < array.length; i++) {
boolean show = true;
for (int j = 0; j < i; j++)
if (array[j] == array[i]) {
show = false;
break;
}
if (show)
System.out.print(array[i] + ", ");
}
}
}
if ((input.nextInt() <= 100) || (input.nextInt() >= 10))
array[i] = input.nextInt();
You are calling nextInt three times which reads the next three integers. So if the user enters 5 then 150, then -1, this will be the same as
if (5 <= 100 || 150 >= 10)
array[i] = -1;
which succeeds when it should not.
You are also using || (or) instead of && (and) so if the user entered 1 after the problem above is fixed, it would look like
if (1 <= 100 ||/* or */ 1 >= 10)
array[i] = 1;
which succeeds because 1 <= 100.
Instead, just read one int and use &&.
int userEnteredInt = input.nextInt();
if (10 <= userEnteredInt && userEnteredInt <= 100)
array[i] = userEnteredInt;

Categories

Resources