Java Minimum and Maximum values in Array - java

My code does not give errors, however it is not displaying the minimum and maximum values. The code is:
Scanner input = new Scanner(System.in);
int array[] = new int[10];
System.out.println("Enter the numbers now.");
for (int i = 0; i < array.length; i++) {
int next = input.nextInt();
// sentineil that will stop loop when 999 is entered
if (next == 999) {
break;
}
array[i] = next;
// get biggest number
getMaxValue(array);
// get smallest number
getMinValue(array);
}
System.out.println("These are the numbers you have entered.");
printArray(array);
// getting the maximum value
public static int getMaxValue(int[] array) {
int maxValue = array[0];
for (int i = 1; i < array.length; i++) {
if (array[i] > maxValue) {
maxValue = array[i];
}
}
return maxValue;
}
// getting the miniumum value
public static int getMinValue(int[] array) {
int minValue = array[0];
for (int i = 1; i < array.length; i++) {
if (array[i] < minValue) {
minValue = array[i];
}
}
return minValue;
}
//this method prints the elements in an array......
//if this case is true, then that's enough to prove to you that the user input has //been stored in an array!!!!!!!
public static void printArray(int arr[]) {
int n = arr.length;
for (int i = 0; i < n; i++) {
System.out.print(arr[i] + " ");
}
}
Do I need a system.out.println() to display it, or should the return work?

getMaxValue(array);
// get smallest number
getMinValue(array);
You are calling the methods but not using the returned values.
System.out.println(getMaxValue(array));
System.out.println(getMinValue(array));

You can try this too, If you don't want to do this by your method.
Arrays.sort(arr);
System.out.println("Min value "+arr[0]);
System.out.println("Max value "+arr[arr.length-1]);

Imho one of the simplest Solutions is:
-
//MIN NUMBER
Collections.sort(listOfNumbers);
listOfNumbers.get(0);
//MAX NUMBER
Collections.sort(listOfNumbers);
Collections.reverse(listOfNumbers);
listOfNumbers.get(0);

Here is the working code to find the min and max in the array.I hope you will find it helpful:
import java.util.Random;
import java.util.Scanner;
public class FindMin {
public static void main(String[] args){
System.out.println("Main Method Started");
Scanner in = new Scanner(System.in);
System.out.println("Enter the size of the arr");
int size = in.nextInt();
System.out.println("Enter the maximum value of the arr");
int max = in.nextInt();
int [] arr = initializeArr(max, size);
print(arr);
findMinMax(arr);
System.out.println("Main Method Ended");
}
public static void print(int[] arr){
for(int val:arr){
System.out.print(val + " ");
}
System.out.println();
}
public static int[] initializeArr(int max,int size){
Random random = new Random();
int [] arr = new int[size];
for(int ii=0;ii<arr.length;ii++){
arr[ii]=random.nextInt(max);
}
return arr;
}
public static void findMinMax(int[] arr){
int min=arr[0];
int max=arr[0];
for(int ii=0;ii<arr.length;ii++){
if(arr[ii]<min){
min=arr[ii];
}
else if(arr[ii]>max){
max=arr[ii];
}
}
System.out.println("The minimum in the arr::"+min);
System.out.println("The maximum in the arr::"+max);
}
}

Sum, Maximum and Minimum value of an Array in One Line
public static void getMinMaxByArraysMethods(int[] givenArray){
//Sum of Array in One Line
long sumofArray = Arrays.stream(givenArray).sum();
//get Minimum Value in an array in One Line
int minimumValue = Arrays.stream(givenArray).min().getAsInt();
//Get Maximum Value of an Array in One Line
int MaxmumValue = Arrays.stream(givenArray).max().getAsInt();
}

You just throw away Min/Max values:
// get biggest number
getMaxValue(array); // <- getMaxValue returns value, which is ignored
// get smallest number
getMinValue(array); // <- getMinValue returns value, which is ignored as well
You can do something like
...
array[i] = next;
System.out.print("Max value = ");
System.out.println(getMaxValue(array)); // <- Print out getMaxValue value
System.out.print("Min value = ");
System.out.println(getMinValue(array)); // <- Print out getMinValue value
...

You are doing two mistakes here.
1. calling getMaxValue(),getMinValue() methods before array initialization completes.
2.Not storing return value returned by the getMaxValue(),getMinValue() methods.
So try this code
for (int i = 0 ; i < array.length; i++ )
{
int next = input.nextInt();
// sentineil that will stop loop when 999 is entered
if (next == 999)
break;
array[i] = next;
}
// get biggest number
int maxValue = getMaxValue(array);
System.out.println(maxValue );
// get smallest number
int minValue = getMinValue(array);
System.out.println(minValue);

your maximum, minimum method is right
but you don't print int to console!
and... maybe better location change (maximum, minimum) methods
now (maximum, minimum) methods in the roop. it is need not.. just need one call
i suggest change this code
for (int i = 0 ; i < array.length; i++ ) {
int next = input.nextInt();
// sentineil that will stop loop when 999 is entered
if (next == 999)
break;
array[i] = next;
}
System.out.println("max Value : " + getMaxValue(array));
System.out.println("min Value : " + getMinValue(array));
System.out.println("These are the numbers you have entered.");
printArray(array);

Yes you need to use a System.out.println. But you are getting the minimum and maximum everytime they input a value and don't keep track of the number of elements if they break early.
Try:
for (int i = 0 ; i < array.length; i++ ) {
int next = input.nextInt();
// sentineil that will stop loop when 999 is entered
if (next == 999)
break;
array[i] = next;
}
int length = i;
// get biggest number
int large = getMaxValue(array, length);
// get smallest number
int small = getMinValue(array, length);
// actually print
System.out.println( "Max: " + large + " Min: " + small );
Then you will have to pass length into the methods to determine min and max and to print. If you don't do this, the rest of the fields will be 0 and can mess up the proper min and max values.

Here you haven't print the max and min values. Print the max and min values in the getMaxVal and getMin val methods or after the call. This is the output.
Enter the numbers now.
5
Max: 5
Min: 0
3
Max: 5
Min: 0
7
Max: 7
Min: 0
3
Max: 7
Min: 0
90
Max: 90
Min: 0
43
Max: 90
Min: 0
100
Max: 100
Min: 0
45
Max: 100
Min: 0
23
Max: 100
Min: 0
22
Max: 100
Min: 3
These are the numbers you have entered.
5 3 7 3 90 43 100 45 23 22
Also when you are declaring an array, it has all 0s initially.

import java.util.*;
class Maxmin
{
public static void main(String args[])
{
int[] arr = new int[10];
Scanner in = new Scanner(System.in);
int i, min=0, max=0;
for(i=0; i<=arr.length; i++)
{
System.out.print("Enter any number: ");
arr[i] = in.nextInt();
}
min = arr[0];
for(i=0; i<=9; i++)
{
if(arr[i] > max)
{
max = arr[i];
}
if(arr[i] < min)
{
min = arr[i];
}
}
System.out.println("Maximum is: " + max);
System.out.println("Minimum is: " + min);
}
}

//To Find Max and Min value in an array without sorting in java
import java.util.Scanner;
import java.util.*;
public class MaxMin_WoutSort {
public static void main(String args[])
{
int n,max=Integer.MIN_VALUE,min=Integer.MAX_VALUE;
System.out.println("Enter the number of elements: ");
Scanner sc = new Scanner(System.in);
int[] arr = new int[sc.nextInt()]; //U can't say static or dynamic.
//UnWrapping object sc to int value;sc.nextInt()
System.out.println("Enter the elements: ");
for(int i=0;i<arr.length;i++) //Loop for entering values in array
{
int next = sc.nextInt();
arr[i] = next;
}
for(int j=0;j<arr.length;j++)
{
if(arr[j]>max) //Maximum Condition
max = arr[j];
else if(arr[j]<min) //Minimum Condition
min = arr[j];
}
System.out.println("Highest Value in array: " +max);
System.out.println("Smallest Value in array: "+min);
}
}

I have updated your same code please compare code with your's original code :
public class Help {
public static void main(String args[]){
Scanner input = new Scanner(System.in);
int array[] = new int[10];
System.out.println("Enter the numbers now.");
for (int i = 0; i < array.length; i++) {
int next = input.nextInt();
// sentineil that will stop loop when 999 is entered
if (next == 999) {
break;
}
array[i] = next;
}
System.out.println("These are the numbers you have entered.");
printArray(array);
// get biggest number
System.out.println("Maximum: "+getMaxValue(array));
// get smallest number
System.out.println("Minimum: "+getMinValue(array));
}
// getting the maximum value
public static int getMaxValue(int[] array) {
int maxValue = array[0];
for (int i = 1; i < array.length; i++) {
if (array[i] > maxValue) {
maxValue = array[i];
}
}
return maxValue;
}
// getting the miniumum value
public static int getMinValue(int[] array) {
int minValue = array[0];
for (int i = 1; i < array.length; i++) {
if (array[i] < minValue) {
minValue = array[i];
}
}
return minValue;
}
//this method prints the elements in an array......
//if this case is true, then that's enough to prove to you that the user input has //been stored in an array!!!!!!!
public static void printArray(int arr[]) {
int n = arr.length;
for (int i = 0; i < n; i++) {
System.out.print(arr[i] + " ");
}
}
}

Related

Creating random integer array without duplicates

I am trying to create a random array without duplicates.
The assignment is to take an integer array and maximum value from user, fills the array with random numbers between 0 and maximum value, and display random array without duplicates, WITHOUT using any other classes except random and scanner.
This is a sample output:
Please enter the size of the array: 10
Please enter the maximum value: 50
[39,2,17,49,12,19,40,31,42,15]
I need help in removing the duplicates. I am not sure if what I am doing is correct, I am a bit of a beginner but here is what I have so far. Help would be greatly appreciated. Thanks.
public class Fill {
private static int size;
private static int maxVal;
public static void main(String[] args) {
Scanner kb = new Scanner(System.in);
// Ask user to enter the size of the array
System.out.print("Please enter the size of the array: ");
size = kb.nextInt();
// Ask user to enter the maximum value allowed
System.out.print("Please enter the maximum value: ");
maxVal = kb.nextInt();
// Call fill() method
int arr[] = fill(size, maxVal);
// Print filled array
System.out.print("[");
for (int i = 0; i < arr.length - 1; i++)
System.out.print(arr[i] + ",");
System.out.print(arr[arr.length - 1] + "]");
}
public static int[] fill(int size, int maxVal) {
int arr[] = new int[size];
Random random = new Random();
// Fills the array with random numbers between 0 and maximum value
if (size <= 0 || maxVal < size - 1) {
System.out.print("Incorrect Parameters. Please Retry");
main(null);
} else {
for (int j = 0; j < size; j++) {
arr[j] = random.nextInt(maxVal);
// Check array for duplicates
for (int k = j + 1; k < size; k++) {
if(arr[j] == arr[k]) {
//create new random array
fill(size, maxVal);
}
}
}
}
return arr;
}
}
I have edited and fixed some issues in your code as below:
public class Fill {
private static int size;
private static int maxVal;
public static void main(String[] args) {
Scanner kb = new Scanner(System.in);
// Ask user to enter the size of the array
System.out.print("Please enter the size of the array: ");
size = kb.nextInt();
// Ask user to enter the maximum value allowed
System.out.print("Please enter the maximum value: ");
maxVal = kb.nextInt();
// Call fill() method
int arr[] = fill(size, maxVal);
// Print filled array
System.out.print("[");
for (int i = 0; i < arr.length - 1; i++)
System.out.print(arr[i] + ",");
System.out.print(arr[arr.length - 1] + "]");
}
public static int[] fill(int size, int maxVal) {
int arr[] = new int[size];
Random random = new Random();
// Fills the array with random numbers between 0 and maximum value
if (size <= 0 || maxVal < size ) {
System.out.print("Incorrect Parameters. Please Retry");
main(null);
} else {
for (int j = 0; j < size; j++) {
int newNumber = random.nextInt(maxVal + 1);
// Check array for duplicates
while(alreadyExist(newNumber, arr)){
newNumber = random.nextInt(maxVal + 1);
}
arr[j] = newNumber;
}
}
return arr;
}
static boolean alreadyExist(int a, int[] arr){
for(int i = 0 ; i < arr.length ; i++){
if(arr[i] == a) return true;
}
return false;
}
}
Now it does not return any repetitive value.

how can i get elements from array which makes sum equals to given value

how can i find lowest number of integers in the array that sums up the given number. The program should ask user to input array of integers (“Input Array”) and the required sum (“Required Sum”). The output (“Output”) should list the lowest number of integers from the input array that sums up the “Required Sum”.
here i create the function sum() and declare array with some elements when read sum from user 45 it gives me output 25,25 but when i input 59 and 60 nothing shows on output
public static void sum()
{
int arr[]={10,0,-1,20,25,30};
Scanner in=new Scanner(System.in);
int sum=in.nextInt();
int[] sub = new int[arr.length];
int temp = 0;
for (int i = 0; i < arr.length; i++)
{
for (int j = i, col = 0; j < arr.length; j++, col++)
{
//add the value of input array one by one
temp += arr[j];
sub[col] = arr[j];
//if addition is equal to sum then print it
if (temp == sum)
{
int total = 0;
for (int k = 0; k < sub.length; k++)
{
total += sub[k];
System.out.println(sub[k]);
//if total and sum are equal then leave the print
if (total == sum)
{
System.out.println();
break;
}
}
}
//if temp is greater than sum are equal then clear the sub array, set temp value and leave the loop for next
if (temp > sum)
{
temp = 0;
break;
}
}
}
}
Output Example:
Input Array : [10, 0, -1, 20, 25, 30]
Required Sum: 45
Output: [20, 25]
Required Sum: 59
Output: [10, -1, 20, 30]
Required Sum: 60
Output: [10, 20, 30]
import java.util.*;
public class Runner
{
public static void find(int[] A, int currSum, int index, int sum,int[] solution)
{
if (currSum == sum)
{
System.out.print("Output: [");
for (int i = 0; i < solution.length; i++)
{
if (solution[i] == 1)
{
if(A[i]!=0)
{
System.out.print(" " + A[i]);
}
}
}
System.out.print(" ]\n");
}
else if (index == A.length)
{
return;
}
else
{
solution[index] = 1;// select the element
currSum += A[index];
find(A, currSum, index + 1, sum, solution);
currSum -= A[index];
solution[index] = 0;// do not select the element
find(A, currSum, index + 1, sum, solution);
}
return;
}
public static void main(String args[])
{
Scanner in =new Scanner(System.in);
System.out.println("How many integer you have to insert: ");
int n=in.nextInt();
int []A=new int[n];
System.out.println("\nEnter elements in Array:\n ");
for(int i=0;i<A.length;i++)
{
A[i]=in.nextInt();
}
System.out.println("\nEnter required sum: ");
int sum=in.nextInt();
int[] solution = new int[A.length];
find(A, 0, 0, sum, solution);
}
}
Please find below program which I feel to be ideal for your scenario.
The Solution might not be optimal with memory and time consideration which you can optimize by based on your scenario.
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
public class Subset {
static public void main (String[] ab)
{
int s[] = {10, 0, -1, 20, 25, 30};
int sum = 45;
ArrayList<ArrayList<Integer>> lis = subsets(s,sum);
Iterator<ArrayList<Integer>> t1 = lis.iterator();
while (t1.hasNext()) {
List<Integer> t2= t1.next();
int count = 0;
Iterator<Integer> t3 = t2.iterator();
while (t3.hasNext()) {
count = count+ t3.next();
}
if(count ==sum)
System.out.println(t2);
}
}
public static ArrayList<ArrayList<Integer>> subsets(int[] S,int sum) {
if (S == null)
return null;
Arrays.sort(S);
ArrayList<ArrayList<Integer>> result = new ArrayList<ArrayList<Integer>>();
for (int i = 0; i < S.length; i++) {
ArrayList<ArrayList<Integer>> temp = new ArrayList<ArrayList<Integer>>();
//get sets that are already in result
for (ArrayList<Integer> a : result) {
temp.add(new ArrayList<Integer>(a));
}
//add S[i] to existing sets
for (ArrayList<Integer> a : temp) {
a.add(S[i]);
}
//add S[i] only as a set
ArrayList<Integer> single = new ArrayList<Integer>();
single.add(S[i]);
temp.add(single);
result.addAll(temp);
}
//add empty set
result.add(new ArrayList<Integer>());
return result;
}
}
Hope this was helpful.
try this code using simple arrays
i created sets from user entered array and print all of them and sets with sum equal to user entered sum i`m showing solution and the element count foe better understanding.
import java.util.*;
public class Main{
public static void set(int[] temp,int sum){
int n=temp.length;
for (int i = 0; i < (1<<n); i++)
{ int sumc=0;
int count=0;
System.out.print("{ ");
// Print current subset
for (int j = 0; j < n; j++)
// (1<<j) is a number with jth bit 1
// so when we 'and' them with the
// subset number we get which numbers
// are present in the subset and which
// are not
if ((i & (1 << j)) > 0) {
System.out.print(temp[j] + " ");
sumc=sumc+temp[j];
count++;
}
if(sum==sumc){
System.out.println("}"+" sum :"+sumc +" solution with "+count+" elements");
}else{
System.out.println("}");
}
}
}
public static void main(String args[]){
Scanner sc=new Scanner(System.in);
System.out.println("enter size of array : ");
int n=sc.nextInt();
int[] a=new int[n];
int sum;
for(int i=0;i<n;i++)
{
System.out.print("enter "+i+" element value of array : ");
a[i]=sc.nextInt();
System.out.println();
}
System.out.println("enter sum : ");
sum=sc.nextInt();
set(a,sum);
}
}
output :
import java.util.*;
public class sum2
{
public static Stack<Integer> find(int A[],int currSum,int index,int sum,int solution[],Stack<Integer> s)
{
if(currSum==sum)
{
int len=s.size();
if(len<=s.size() )
{
s.clear();
}
for(int i=0;i<solution.length;i++)
{
if(solution[i]==1) {
if(A[i]!=0 )
{
s.push(A[i]);
}
}
}
len=s.size();
return s;
}
else if(index==A.length)
{
return s ;
}
else
{
solution[index]=1;
currSum+=A[index];
find(A,currSum,index+1,sum,solution,s);
currSum-=A[index];
solution[index]=0;
find(A,currSum,index+1,sum,solution,s);
return s;
}
}
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
System.out.print("Enter Array size");
int size=sc.nextInt();
int A[] =new int[size];
System.out.println("Enter elements");
for(int i=0;i<A.length;i++)
{
A[i]=sc.nextInt();
}
System.out.println("Enter sum");
int sum=sc.nextInt();
int solution[]=new int[A.length];
Stack<Integer> s=new Stack<Integer>();
Arrays.sort(A);
find(A,0,0,sum,solution,s);
System.out.print("Output:" +s);
}
}
It took almost 3 days

How do I get a specific component of an array that doesn't have set length?

What I'm trying to do is get a set of numbers from the user, the console will print out the second highest number in english and the second lowest number in spanish.
First I'm trying to get the input from user, put it in an array and grab the second highest and second lowest value of the components. But I can't figure out how to grab ones I need.
public static void main(String[] args) {
//get the length from user
int length;
Scanner input = new Scanner(System.in);
System.out.println("How many variables are you going to enter?: ");
length = input.nextInt();
//allocate array for that length
int[] variables = new int[length];
for(int counter = 0; counter < length; counter++) {
System.out.println("Enter variable: ");
variables[counter] = input.nextInt();
}
input.close();
//print the variables
System.out.println("Your variables are");
for(int counter = 0; counter < length; counter++) {
System.out.println(variables[counter]);
}
}
System.out.println("------------------");
Arrays.sort(variables); //sort array
System.out.println(variables[1]); //2nd lowest value
System.out.println(variables[variables.length-2]); //2nd highest value
try this brother
add this to your code
class Demo
{
public static void findNum(int arr[]){
int largest = arr[0], second_largest = arr[0];
int minimum = are[0], second_minimum = are[0];
for(int i=0;i<arr.length;i++){
if(arr[i] >= largest){
second_largest = largest;
largest = arr[i];
}
else if(arr[i]>second_largest){
second_largest = arr[i];
}
if(arr[i] <= minimum){
second_minimum = minimum;
minimum = arr[i];
}
else if(arr[i]<second_minimum){
second_minimum = arr[i];
}
}
System.out.println("Second Largest = " + second_largest + " Second_minimum = "+second_minimum);
}
public static void main (String[] args) throws java.lang.Exception
{
int arr[] = {5,3,2,1,8,77};
findNum(arr);
}
}
You can do something like this if you're particular about not sorting your original array.

Displaying odd values in an array

I am trying to display the odd numbers in an array, but only once per number (i.e. numbers[3] = 3,3,1; would only display 3 and 1 instead of 3, 3 and 1.)
this is the code that I have as of now, the program completely will create an with the specific length entered by the user and then will calculate the max min, and odd values in the array.
import java.util.Scanner;
public class ArrayLab
{
static Scanner input = new Scanner (System.in);
public static void main(String[] args)
{
System.out.println("Enter the number of numbers: ");
final int NUMBER_OF_ELEMENTS = input.nextInt();
double[] numbers = new double[NUMBER_OF_ELEMENTS];
System.out.println("Enter the numbers: ");
for (int i = 0; i < NUMBER_OF_ELEMENTS; i++)
{
numbers[i] = input.nextDouble();
}
input.close();
double max = numbers[0];
double min = numbers[0];
for (int i = 0; i < NUMBER_OF_ELEMENTS; i++)
{
if (numbers[i] > max)
{
max = numbers[i];
}
}
System.out.println("The max is: " + max);
for (int i = 0; i < NUMBER_OF_ELEMENTS; i++)
{
if (numbers[i] < min)
{
min = numbers[i];
}
}
System.out.println("The min is: " + min);
for (int i = 0; i < NUMBER_OF_ELEMENTS; i++)
{
if (numbers[i] % 2 != 0)
{
System.out.println ("The odd numbers are: " + numbers[i]);
}
}
}
}
thanks for any help.
Set<Integer> set = new HashSet<Integer>();
for (int i = 0; i < NUMBER_OF_ELEMENTS; i++)
{
if (numbers[i] % 2 != 0)
{
set.add(numbers[i]);
}
}
System.out.println ("The odd numbers are: " +set);
This can be done a lot simpler using Java8:
double[] d = Arrays.toStream(numbers).filter(d -> (d % 2) == 1).distinct().toArray();
for(double tmp : d)
System.out.println(tmp);
System.out.println("min: " + Arrays.toStream(numbers).min((a , b) -> new Double(a).compareTo(b)));
System.out.println("max: " + Arrays.toStream(numbers).max((a , b) -> (new Double(a).compareTo(b))));
For you're solution: you never eliminate repeating numbers, thus the duplicates remain in the array until you print all odd numbers and the maximum-number.
This elimination can be done in several ways:
Using Java8 as above
add all values to a Set, since these don't allow duplicate values
eliminate them in your own way (i won't provide any code for this since it's rather complicated to design an efficient solution for this)
Updated solution for what you need. And Please use a better coding standard. Do note the condition check !oddNumbers.contains(numbers[i]) is not very necessary as HashSet never takes any duplicate values.
import java.util.HashSet;
import java.util.Scanner;
public class ArrayLab {
static Scanner input = new Scanner(System.in);
public static void main(String[] args) {
System.out.println("Enter the number of numbers: ");
final int NUMBER_OF_ELEMENTS = input.nextInt();
double[] numbers = new double[NUMBER_OF_ELEMENTS];
System.out.println("Enter the numbers: ");
for (int i = 0; i < NUMBER_OF_ELEMENTS; i++) {
numbers[i] = input.nextDouble();
}
input.close();
HashSet<Double> oddNumbers = new HashSet<Double>(NUMBER_OF_ELEMENTS);
double max = numbers[0];
double min = numbers[0];
for (int i = 0; i < NUMBER_OF_ELEMENTS; i++) {
if (numbers[i] > max) {
max = numbers[i];
}
if (numbers[i] < min) {
min = numbers[i];
}
if (numbers[i] % 2 != 0 && !oddNumbers.contains(numbers[i])) {
oddNumbers.add(numbers[i]);
}
}
System.out.println("The max is: " + max);
System.out.println("The min is: " + min);
System.out.println("The odd numbers are: " + oddNumbers);
}
}
A more meaningful solution to your approach would be as follows:
int[] tempArray; //temporary array to store values from your original "array"
int count=0;
for(int i=0; i<numbers.length; i++) {
if(numbers[i]%2 != 0) {
count++;
}
}
tempArray = new int[count]; //initializing array of size equals to number of odd digits in your array
int j = 0;
for(int i=0; i<numbers.length; i++) {
boolean check = true;
for(int k=0; k<j; k++) {
if(tempArray[k] == numbers[i]) {
check = false; //this will prevent duplication of odd numbers
}
}
if(numbers[i]%2 != 0 && check) {
tempArray[j]=numbers[i];
j++;
}
}
//Now print the tempArray which contains all the odd numbers without repetition
A few people have mentioned sets, but there is a different way as well. Simply sort the array, then scan through it, checking each number against the last one printed. i.e.,
int lastPrinted = 0;
// Sort the array
Arrays.sort(numbers);
System.out.print("The odd numbers are: ");
// Scan through the array
for (int i = 0; i < NUMBER_OF_ELEMENTS; i++)
{
// if it's odd and doesn't match the last one...
if (numbers[i] % 2 != 0 && numbers[i] != lastPrinted)
{
// ...print it and update lastPrinted
System.out.print( "" + numbers[i] );
lastPrinted = numbers[i];
}
}
System.out.println("");
As a side note, you really don't have to scan through the array twice to find your max and min, you can do that in one go.
I think you can use inbuilt hashmap class and its method to achieve the task without affecting the complexity of algorithm to any great extent .
import java.util.HashMap;
public class Hashing {
public static void main(String[] args) {
//declare a new hasmap
HashMap<Integer, Integer> map = new HashMap<>();
//consider Arr as your Array
int Arr[] = {3,3,1,4,5,5,7,8};
//traverse through the array
for(int i=0;i<Arr.length;i++){
//check if the required condition is true
if(Arr[i]%2==1){
/*now we insert the elements in the map but before
that we have to make sure that we don't insert duplicate values*/
if(!map.containsKey(Arr[i])){// this would not affect the complexity of Algorithm since we are using hashMap
map.put(Arr[i], Arr[i]);//We are storing the Element as KEY and as VALUE in the map
}
}
}
//now We can get these element back from map by using the following statement
Integer[] newArray = map.values().toArray(new Integer[0]);
//All the required elements are now present in newArray
for(int ele:newArray){
System.out.println(ele);
}
}
}

returning a value not working correctly? (basic Java)

In this program, I must have user input value for variable (N). In method 1, user will input 10 numbers into an array. In method 2, it will compare variable (N) and save all numbers larger than that variable to (greaterNums) variable. Having some return and sending problems, even though I have read chapter over and over. Someone please point me in the right direction!
Problem 1: greaterNums variable value isn't correct after the arguments in method 2.
Problem 2: greaterNums variable isn't returning to main method to be displayed.
import javax.swing.JOptionPane;
public class Project6Walker
{
public static void main(String[] args)
{
final int ARRAY_SIZE = 10; //Establish array size
int n; //Holds comparable value
String input; //Holds user input
int[] array = new int[ARRAY_SIZE]; //Establishes array
input = JOptionPane.showInputDialog("Enter a number. Must not be a negative number.");
n = Integer.parseInt(input); //Gather value N
while (n < 0) //INPUT VALIDATION for N
{
input = JOptionPane.showInputDialog("Must not be a negative number. Please try again.");
n = Integer.parseInt(input);
}
gatherArrayInformation(array, input); //Calls method 1
compareArrayInformation(array, n); //Calls method 2
JOptionPane.showMessageDialog(null, "The numbers in the array that are "+
"greater than " +n+ " are (greaterNums goes here)."); //Final output of information
/**
This method will prompt the user to enter 10 numbers in the array
that will be compared to the value N
*/
}
public static int[] gatherArrayInformation(int[] array, String input)
{
JOptionPane.showMessageDialog(null, "Enter series of " + array.length + " numbers");
for (int i= 0; i < array.length; i++)
{
input = JOptionPane.showInputDialog("Number " + (i + 1) + ":");
array[i] = Integer.parseInt(input);
while (array[i] < 0)
{
input = JOptionPane.showInputDialog("Number " + (i + 1) + " cannot be negative. Try Again.");
array[i] = Integer.parseInt(input);
}
System.out.print(array[i] + " ");
}
return array;
}
/**
This method will take the 10 numbers from method 1,
and see which numbers are larger than N
#return greaterNums
*/
public static int compareArrayInformation(int[] array, int n)
{
int greaterNums = 0;
for (int i= 1; i < array.length; i++)
{
if (array[i] > n)
greaterNums = array[i];
System.out.println(greaterNums);
}
return greaterNums;
}
}
Problem 2: When you return greaterNums, as your code currently stands, it's just returning the array member with the highest index that was bigger than n.
Array indices start from 0.
public static List<Integer> compareArrayInformation(int[] array, int n)
{
List<Integer> greaterNums = new ArrayList<>();
for (int i = 0; i < array.length; i++) // Count from 0
{
if (array[i] > n) {
int greaterNum = array[i];
System.out.println(greaterNum);
greaterNums.add(greaterNum);
}
}
return greaterNums;
}
And to collect all greater numbers, one better uses no fixed sized array, int[], but a List<Integer>.
Replace your function compareArrayInformation to below
public static int compareArrayInformation(int[] array, int n)
{
int[] greaterNums = new int[10];
for (int i= 0; i < array.length; i++)
{
if (array[i] > n)
{
greaterNums.add(array[i]);
}
}
return greaterNums;
}
and in your main method change the below lines FROM
compareArrayInformation(array, n);
JOptionPane.showMessageDialog(null, "The numbers in the array that are "+
"greater than " +n+ " are (greaterNums goes here).");
TO
int[] greaterNumsArray = compareArrayInformation(array, n);
StringBuffer sBuffer = new StringBuffer("");
for (int i=0; i<greaterNumsArray.length; i++){
sBuffer.append(greaterNumsArray[i]);
}
JOptionPane.showMessageDialog(null, "The numbers in the array that are "+
"greater than " +n+ " are "+sBuffer );
this program will work with i set to 0 not one but it will of course only show THE LAST GREATER NUMBER not nums hope that is what you wanted.
public static int compareArrayInformation(int[] array, int n)
{
int greaterNums = 0;
for (int i= 0; i < array.length; i++)//not one
{
if (array[i] > n)
greaterNums = array[i];
System.out.println(greaterNums);
}
return greaterNums;
}
maybe you want this?
public static int[] compareArrayInformation(int[] array, int n)
{
int[] greaternums=new int[array.length];
int upto=0;
for (int i= 0; i < array.length; i++)//not one
{
if (array[i] > n)
greaternums[upto] = array[i];
System.out.println(array[i]);
upto++;
}
return Arrays.copyOf(greaternums, upto);
}

Categories

Resources