How to find second highest number in array in java [duplicate] - java

This question already has answers here:
Finding the second highest number in array
(45 answers)
Closed 3 years ago.
I want to find second highest number in array in java.
I tied to solve problem from this code.
class Example{
public static void main(String args[]){
Scanner input=new Scanner(System.in);
//Random r=new Random();
int max=0;
int secondMax = 0;
for(int i=0; i<10; i++){
System.out.print("Input an integer : ");
int num = input.nextInt();
if (num>max)
{
secondMax=max;
max=num;
}
}
System.out.println("Max number is : "+max);
System.out.println("Second Max number is : "+secondMax);
}
}

You're trying to find the max and second values while populating the array. Try removing
if (num>max)
{
secondMax=max;
max=num;
}
from the for loop. Then add a separate (not nested) for loop to search the array:
for (int i = 0; i < 10; i++){
if (input[i] > max){
secondMax = max;
max = input[i];
}
if ((input[i] < max) && (input[i] > secondMax))
secondMax = input[i];
}

import java.util.*;
class Example{
public static void main(String args[]){
Scanner input=new Scanner(System.in);
int []numbers=new int[10];
for (int i = 0; i <10 ; i++)
{
System.out.print("Input an integer: ");
numbers[i]=input.nextInt();
}
int max=0;
int secondHighest=0;
for (int i = 0; i < numbers.length; i++)
{
if (numbers[i]>max)
{
secondHighest=max;
max=numbers[i];
}
if (numbers[i]<max && numbers[i]>=secondHighest )
{
secondHighest=numbers[i];
}
}
System.out.println("Max number is : "+max);
System.out.println("Second highest number is : "+secondHighest);
}
}

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

Trying to get a For Loop to work

I'm trying to write a program where on the first line, you enter the number of times you want a for loop to iterate, on the second line, you enter the value of the array, and on the third line, you enter the numbers that you want in the array. My program either does not do what I want it to do, or it crashes on me. This is the code that I have for the program so far:
import java.util.*;
public static void main(String[] args) {
Scanner input = new Scanner (System.in);
int n = input.nextInt();
for (int i=0; i<n; i++)
{
int value = input.nextInt();
int[] arr = new int[value];
arr[i] = input.nextInt();
}
}
What can I do? Please help. I've tried everything! Also, it would help if someone could help me with sorting the numbers in ascending order, followed by displaying the middle number in each line, but first thing's first. Thank you.
I believe this is more of what you are after. I output the entries individually but you could combine that easily enough.
public static void main(String[] args)
{
Scanner input = new Scanner (System.in);
try
{
System.out.println("Number of times to loop:");
int numEntries = input.nextInt();
int[][] valueArrays = new int[numEntries][];
for (int i=0; i<numEntries; i++)
{
System.out.println("Size of array #"+i+": ");
int arrayLen = input.nextInt();
int[] inputArray = new int[arrayLen];
for (int j = 0; j < arrayLen; j++)
{
System.out.println("Enter value at index "+j+": ");
inputArray[j] = input.nextInt();
}
Arrays.sort(inputArray);
valueArrays[i] = inputArray;
}
for (int l=0; l < valueArrays.length; l++)
{
int[] values = valueArrays[l];
for (int m=0; m < values.length; m++)
{
System.out.println("Value of array #"+l+" saved at index "+m +": " + values[m]);
}
if ((values.length % 2) == 0)
{
int start = values.length/2;
int end = start + 1;
System.out.println("Middle values in array #"+l+" saved at indices " + start + " and " + end);
}
else
{
int start = values.length/2;
System.out.println("Middle value in array #"+l+" saved at index " + start);
}
}
}
finally
{
input.close();
}
}
You're creating a new array on each iteration inside the loop.
You should get int[] arr = new int[value]; out of the loop:
int arraySize = input.nextInt();
int[] arr = new int[arraySize];
for (int i=0; i<arraySize; i++)
{
int value = input.nextInt();
arr[i] = value;
}
If you don't want to limit the user for a size, use an ArrayList instead.
Problem 1:My program either does not do what I want it to do.
Dont initialize array inside for loop as loop wiil create a new array every time you iterate it.
Scanner input = new Scanner (System.in);
System.out.println("Enter no. of elements in array");
int n = input.nextInt();
int[] arr = new int[n];
System.out.println("Array length set to "+n);
for (int i=0; i<n; i++)
{
System.out.println("Enter value for index "+i);
arr[i] = input.nextInt();
System.out.println(arr[i]+" Value saved at index "+i);
}
DEMO1
Problem 2(described in comments below):Sorting arrays and displaying the middle number
class Ideone
{
static int[] countingSort(int[] numbers) {
int max = numbers[0];
for (int i = 1; i < numbers.length; i++) {
if (numbers[i] > max)
max = numbers[i];
}
int[] sortedNumbers = new int[max+1];
for (int i = 0; i < numbers.length; i++) {
sortedNumbers[numbers[i]]++;
}
int insertPosition = 0;
for (int i = 0; i <= max; i++) {
for (int j = 0; j < sortedNumbers[i]; j++) {
numbers[insertPosition] = i;
insertPosition++;
}
}
return numbers;
}
public static void main (String[] args) throws java.lang.Exception
{
Scanner input = new Scanner (System.in);
System.out.println("Number of times to loop:");
int n = input.nextInt();
// int[] arr = new int[n];
// System.out.println("Array length set to "+n);
for (int i=1; i<=3; i++)
{
System.out.println("Size of array #"+i+": ");
int alen = input.nextInt();
int[] arr = new int[alen];
System.out.println("Value in array #"+i+": ");
for (int j=0; j<alen; j++){
System.out.println("Enter value at index "+j+": ");
arr[j] = input.nextInt();
}
arr=Ideone.countingSort(arr);
for (int l=0; l<alen; l++)
System.out.println(arr[l]+" Value of array #"+i+" saved at index "+l);
System.out.println("Middle value in array #"+i+" saved at index "+arr[alen/2]);
}
}
}
DEMO2

Java Sorting Array

I have this code and I do not know why the selection sort is not sorting all the way Does anyone know where to fix the program. The selection sort code I believe is right i just dont know what is wrong. The code is functioning
import java.util.Scanner;
public class selectionSort
{
public static void main(String[] args)
{
Scanner scanner = new Scanner(System.in);
int temp;
int i,j,first;
System.out.println("How many numbers do you want to enter?");
int ammount = scanner.nextInt();
int[]array = new int[ammount];
for (i = 0 ; i < array.length; i++ )
{
System.out.println("Enter the numbers now.");
array[i] = scanner.nextInt();
}
System.out.println("\nThe array is:");
for(i = 0; i < array.length; i++){
System.out.print(array[i] + " ");
}
for (i=array.length - 1; i>0;i--)
{
first=0;
for(j=1;j<=1;j++)
{
if(array[j]<array[first])
first = j;
}
temp = array[first];
array[first] = array[i];
array[i]=temp;
}
System.out.println("\nThe sorted array is:");
for( i = 0; i < array.length; i++){
System.out.print(array[i] + " ");
}
}
}
You appear to have a typo. This line:
for(j=1;j<=1;j++)
should probably be:
for(j=1;j<=i;j++)
(The loop termination test should be j<=i, not j<=1.)

Categories

Resources