Removing duplicate elements from Array in Core Java - java

Without using collections,i have written a java program to remove duplicate integer element from an integer array,however the program is removing only one integer element and other integer element is left over.
Could you let me know how should i remove duplicate integer elements in the below core java program.In the below core java program i have to remove the duplicate integer element 5
Help provided will be appreciated.
Below is the Java code.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class DeleteElementFromArray {
static int[] a = {5,1,2,3,4,5,7,8,9,10};
static int[] b = new int[10];
static int i, k, f, j = 0;
static int l = a.length;
void DeletElementInt() {
for (i = 0; i < l; i++) {
if (i != k) {
if (i < k) {
b[i] = a[i];
} else{
b[i - 1] = a[i];
}
}
}
}
public static void main(String[] args) {
DeleteElementFromArray d = new DeleteElementFromArray();
System.out.println("Array Elements are ");
for (i = 0; i < l; i++){
System.out.println(a[i]);
}
InputStreamReader is = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(is);
System.out.println("Enter the Element for Delete");
try {
String s = br.readLine();
f = Integer.parseInt(s);
for (i = 0; i < l; i++) {
if (f == a[i]) {
System.out.println("Delete Element found from given array");
k = i;
j++;
d.DeletElementInt();
}
}
l = l - 1;
System.out.println("New Array ");
for (i = 0; i < l; i++)
{
System.out.println(b[i]);
}
if (j == 0) {
System.out.println("Entered Element does not found from given array");
}
} catch (IOException e) {
System.out.println(e);
}
}
}
//output
/*
Array Elements are
5
1
2
3
4
5
7
8
9
10
Enter the Element for Delete
5
Delete Element found from given array
New Array
1
2
3
4
5
7
8
9
10
*/

Here is the fixed code:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class DelElem {
static int[] a = {5,1,2,3,4,5,7,8,9,10};
static int[] b = new int[10];
static int f, i, k, j = 0;
static int l = a.length;
static void DeleteElementInt(int elementToDelete) {
j = 0;
for (int i = 0; i < l; i++)
if (a[i] != elementToDelete)
b[i - j] = a[i];
else
++j;
}
public static void main(String[] args) {
System.out.println("Array elements are:");
for (i = 0; i < a.length; i++)
System.out.println(a[i]);
InputStreamReader is = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(is);
System.out.print("Enter the element to be deleted: ");
try {
String s = br.readLine();
f = Integer.parseInt(s);
DeleteElementInt(f);
System.out.println("New array:");
for (i = 0; i < l - j; i++)
System.out.println(b[i]);
if (j == 0)
System.out.println("Entered element was not found in the given array");
} catch (IOException e) {
System.out.println(e);
}
}
}
//output
/*
Array elements are:
5
1
2
3
4
5
7
8
9
10
Enter the element to be deleted: 5
New array:
1
2
3
4
7
8
9
10
*/

First you have to sort your array. It will be much easier for you to remove the duplicates if you do. The Arrays class contains various methods (most of them are static) to manipulate arrays. Use Arrays.sort(array). If you're not allowed to, you have to use one of the many existing sorting algorithm. The simplest being Bubble sort.
Insert the first integer in your result array, and in a temporary variable which will contain the last inserted value. Parse the source array: if the current value is different than the temporary var, insert it in the result array (and update the temp var).
Be careful with the size of your return array.

is Arrays.sort() okay?
static int[] a = {5,1,2,3,4,5,7,8,9,10};
static int[] b = new int[a.length];
Arrays.sort(a);
b[0]=a[0];
int bIndex = 1;
for(int aIndex = 1; aIndex < a.length; aIndex++) {
if(b[bIndex-1] != a[aIndex]) {
b[bIndex] = a[aIndex];
bIndex++;
}
}
int[] result = Arrays.copyOfRange(b, 0, bIndex);
if this is for educational purposes another interesting approach could be to construct a tree structure with the numbers and flatten the tree to an array when all inserts are done.

The first question when some one ask you to work with arrays should be. Do the order is important ?
Most problem with arrays can be solved by sorting it first and then the problem is reduced to trivial from complex as you always work on the same type of data. As Archimedes sad once "Give me a place to stand on, and I will move the Earth". The sort operation is that stand place.
When you sort your array, then you just need to traverse it and find that next item is equal to previous. This is trivial.
How ever if the order is important then we have a little bit harder task.
So first solution that pop i my mind is to create new point to stand. The rules are that array has items grater or equal then zero.
In this case we could do something like this.
We find the grates element in our source array.
We create a boolean array with size of grates item.
We move through each item of source list and
We check that boolean arrays position of value has false if so then we set it to true an print the result else we go to next item of source array.
The step 4 was simplified as we want to print the list. The technical aspect of returning new one with distinct values is trivial to.
So good luck.

import java.util.Scanner;
public class RemoveAllOccurences{
static int[] removeAll(int[] a,int n){
int[] dupl = new int[a.length];
for(int i = 0;i < dupl.length;i++){
dupl[i] = -999;
}
int index = 0;
//looping over,finding all occurrences of n and creating new array that does not contain n.
for(int i = 0;i < a.length;i++){
if(a[i] != n){
dupl[index++] = a[i];
}
}
//returning array with all duplicates removed.
return dupl;
}
public static void main(String[] args) {
int[] a = {3,5,5,5,3,6,5,3,3};
int numberToRemove;
System.out.println("the array values are:");
for(int i:a){
System.out.print(a[i]+"\t");
}
Scanner sc = new Scanner(System.in);
System.out.println("\nenter the number for which all occurences need to be deleted:");
numberToRemove = sc.nextInt();
int[] b = removeAll(a,numberToRemove);
System.out.println("After removing all occurences of "+numberToRemove);
for(int i:b){
if(i != -999)
System.out.print(i+"\t");
}
}
}

Below is my solution:
First step:- Iterate through array with nested loops to find duplicates
Second step:- If found duplicates copy all elements in new array except duplicate element.
Please find below code, any improvement would be appreciated.
public class DuplicateElements {
private static int[] arr = new int[]{3,2,4,4,5,3,8,2,4,9,10};
public static void main(String[] args) {
for(int i=0;i<arr.length;i++){
int arr_i = arr[i];
for(int j=0;j<arr.length;j++){
if(arr_i == arr[j] && i != j){
removeElement(j);
}
}
}
for(int i=0;i<arr.length;i++){
System.out.print(arr[i]+", ");
}
}
public static void removeElement(int position){
int[] intArr = new int[arr.length - 1];
for(int i=0;i<position;i++){
intArr[i] = arr[i];
}
for(int i=position+1;i<arr.length;i++){
intArr[i-1] = arr[i];
}
arr = intArr;
}
}

public static void main(String[] args) {
int a[]={1,4,3,2,6,5,7,3,5,4,2};
int b[]=new int[a.length];
Arrays.sort(a);
int j=0;
for(int i=0;i<a.length;i++){
while(i<a.length-1 && a[i]==a[i+1]){
a[i]=999; // This can be any tag which you are not going to have in your array
i++;
}
if(a[i]!=999)
b[j++]=a[i];
}
System.out.println(b);
}

Use:
package Array;
import java.util.Scanner;
public class DuplicateArrayElement {
//operation
void duplicate(int arr[],int size) {
int count=0;
for(int i=0;i<size-1;i++) {
for(int j=i+1;j<size;j++) {
if(arr[i]==arr[j]) {
arr[i]=0;
count++;
}
}
}
for(int i =0; i<size;i++) {
if(arr[i]!=0) {
System.out.println(" "+arr[i]);
}
}
System.out.println("Total duplicate number : "+count);
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
DuplicateArrayElement duplicateArrayElement = new DuplicateArrayElement();
try {
System.out.println("Enter the size of array:");
int size = input.nextInt();
int arr[] = new int[size];
System.out.println("Enter the elements: ");
for (int i = 0; i < size; i++) {
arr[i] = input.nextInt();
}
System.out.println("Orignal Array: ");
for (int i : arr) {
System.out.print(" " + i);
}
System.out.println("\nAfter removing duplicate values :");
duplicateArrayElement.duplicate(arr, size);
} catch (ArrayIndexOutOfBoundsException ex) {
System.out.println(ex);
} finally {
input.close();
}
}
}

Related

Moving specific elements of an array from one array to another of different size

I was asked to
Create a method with a single parameter, an array of integers, that will return an array of integers. Count how many odd values exists within the array. Create a new array with that many elements. Place all the odd values into this new array ( that is all odd values from the array passed through as a parameter ). Return this new array
but I am having some difficulty in transferring the odd values into the new array. I can get the correct size based on the number of odd values in the first array but right now they appear as zeros. Here is the code:
import java.util.Scanner;
public class Main {
public static int output(int[]beans){
int sum = 0;
for (int p = 0; p < beans.length; p++){
if(beans[p]%2 != 0){
sum++;
}
}
System.out.print("The number of odd vaules in this array are: "+sum);
System.out.println();
int[] notbeans = new int[sum];
System.out.print("The odd values within the first array are: ");
for (int index = 0; index < beans.length; index++){
if( beans [index] %2 != 0){
System.out.print(beans[index]);
}
}
System.out.println();
for (int g = 0; g < notbeans.length; g++){
System.out.print(notbeans[g]);
}
return notbeans[1];
}
public static void main(String[] args) {
Scanner key = new Scanner(System.in);
int[]array = new int[5];
for (int t = 0; t < array.length; t++){
System.out.print("Enter an integer: ");
array[t] = key.nextInt();
}
output(array);
}
}
According to your question, method output needs to...
Return this new array
Hence method output needs to return int[] (and not int).
After counting the number of odd values in the array passed to method output and creating the array that the method needs to return, in order to populate the returned array, you need to maintain a second [array] index. You are using the same index to populate the returned array and to iterate the array parameter. The returned array may be smaller in size, i.e. contain less elements, than the array parameter so using the same index for both arrays may cause method output to throw ArrayIndexOutOfBoundsException. In any method, you should also always check whether the method parameters are valid.
import java.util.Arrays;
import java.util.Scanner;
public class Main {
public static int[] output(int[] beans) {
int sum = 0;
if (beans != null && beans.length > 0) {
for (int p = 0; p < beans.length; p++) {
if (beans[p] % 2 == 1) {
sum++;
}
}
}
int[] notBeans = new int[sum];
int j = 0;
for (int index = 0; index < beans.length; index++) {
if (beans[index] % 2 == 1) {
notBeans[j++] = beans[index];
}
}
return notBeans;
}
public static void main(String[] args) {
Scanner key = new Scanner(System.in);
int[] array = new int[5];
for (int t = 0; t < array.length; t++){
System.out.print("Enter an integer: ");
array[t] = key.nextInt();
}
System.out.println(Arrays.toString(output(array)));
}
}
Your output function should return an array, so return type will not be int. It will be int[]. See the below code and let me know.
public class Main {
public static void main(String[] args) {
Scanner key = new Scanner(System.in);
int[]array = new int[5];
for (int t = 0; t < array.length; t++){
System.out.print("Enter an integer: ");
array[t] = key.nextInt();
}
int[] arr=output(array);
for(int i=0;i<arr.length;i++){
int val=arr[i];
if(val!=0){
System.out.println(val);
}
}
}
public static int[] output(int[]beans){
int[] notBeans=new int[beans.length];
int i=0;
for(int v:beans){
if(v%2!=0){
notBeans[i]=v;
i++;
}
}
return notBeans;
}
}

Storing output of a nested loop as new array - Java

I need to find the largest prime number of a given array when adding two numbers in an array,so I decided to add all possible sums first and displayed it. Now I want to take those output elements to a new array.Please help me solve this problem.
import java.util.Scanner;
public class main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int noOfElem = scanner.nextInt();
int[] array = new int[noOfElem];
int[][] newArray = new int[5][4];
int i=0;
while(scanner.hasNextInt()){
array[i] = scanner.nextInt();
i++;
if(i == noOfElem){
break;
}
}
for (int a = 0; a < array.length; a++)
{
for (int b = a+1; b < array.length; b++) {
int m = array[a] + array[b];
newArray[a][b] =
}
}
}
}
Not quite sure what the problem is here, just do
newArray[a][b] = m;
This stores all sums of all 'a's and 'b's such that newArray[a][b] is the sum of array[a] + array[b]

How to get all sub arrays of specific length from array

If I have array like [1,2,3,4] and k = 3 then output should be
[1,2,3][2,3,4][1,3,4] which is in sorted order.
I can do it when k = 2 but can't think of a way to do it more generic for any value of k.
final int arr[] = new int[] { 1, 2, 3, 4 };
final int max = 2;
for (int i = 0; i < arr.length - 1; i++) {
for (int j = i + 1; j < arr.length; j++) {
for (int k = 0; k < max; k = k + 2) {
System.out.println(i + "" + j);
}
}
}
As I said above try to convert array to ArrayList, sort it.
Imagine that now you have an original paper with list of your integer values.
You copy this paper, cross off one of the integer values in copy and put this paper into your folder (HashSet in the following code). Then copy original again and so on.
package Subarrays;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Scanner;
import java.util.Set;
public class Subarrays {
public static void main(String[] arg) {
int arraySize = 0;
int initElementNumber = 0;
int initElementValue = 0;
Scanner scanner = new Scanner(System.in);
// Creates an array
System.out.println("Type the size of the array: ");
do {
try {
arraySize = scanner.nextInt();
} catch (Exception e) {
e.printStackTrace();
}
} while (arraySize == 0);
System.out.println("Type the number of element, which you want to initialize yourself: ");
do {
try {
initElementNumber = scanner.nextInt();
} catch (Exception e) {
e.printStackTrace();
}
} while (initElementNumber == 0);
System.out.println("Type value of the element: ");
do {
try {
initElementValue = scanner.nextInt();
} catch (Exception e) {
e.printStackTrace();
}
} while (initElementValue == 0);
Integer arr[] = new Integer[arraySize];
arr[initElementNumber] = initElementValue;
for (int i = 0; i < arr.length; i++) {
if (i != initElementNumber) {
arr[i] = i;
}
}
// Converts the array to arrayList
ArrayList<Integer> list = new ArrayList<Integer>(Arrays.asList(arr));
// Sorts the list
Collections.sort(list);
// Creates a clone of the list
ArrayList<Integer> listTemp = (ArrayList<Integer>) list.clone();
// Creates a set of the future lists
Set<ArrayList<Integer>> set = new HashSet<ArrayList<Integer>>();
// Iterates over the list and removes one element
for (int i = 0; i < list.size(); i++) {
listTemp.remove(i); // listTemp restructured here
// Adding listItem to set
set.add(listTemp);
// Creates new clone of the list
listTemp = (ArrayList<Integer>) list.clone();
}
// Writes content of the set to the console
for (List<Integer> list2 : set) {
System.out.print("List: ");
for (Integer integer2 : list2) {
System.out.print(" " + integer2 + " ");
}
System.out.println();
}
}
}
Result of the executing of the code will be:
Type the size of the array:
5
Type the number of element, which you want to initialize yourself:
2
Type value of the element:
8
List: 0 3 4 8
List: 0 1 4 8
List: 1 3 4 8
List: 0 1 3 8
List: 0 1 3 4
UPDATE:
I read your question more attentively and decided to rewrite the code for meeting the main requirement: find all sorted subarrays with size k in the array with size n.
package Subarrays;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Scanner;
import java.util.Set;
public class Subarrays2 {
private static int ARRAY_SIZE = 0;
private static int SIZE_OF_SUBARRAYS = 0;
private static Set<ArrayList<Integer>> set = new HashSet<ArrayList<Integer>>();
public static void main(String[] arg) {
Scanner scanner = new Scanner(System.in);
// Creates an array
System.out.println("Type the size of the array: ");
do {
try {
ARRAY_SIZE = scanner.nextInt();
} catch (Exception e) {
e.printStackTrace();
}
} while (ARRAY_SIZE == 0);
System.out.println("Type the size of subarrays: ");
do {
try {
SIZE_OF_SUBARRAYS = scanner.nextInt();
} catch (Exception e) {
e.printStackTrace();
}
} while (SIZE_OF_SUBARRAYS == 0);
scanner.close();
Integer arr[] = new Integer[ARRAY_SIZE];
for (int i = 0; i < ARRAY_SIZE; i++) {
arr[i] = i;
}
// Converts the array to arrayList
ArrayList<Integer> list = new ArrayList<Integer>(Arrays.asList(arr));
// Sorts the list
Collections.sort(list);
recursion(list); // This method work until find all of the sorted lists
// with size SIZE_OF_SUBARRAYS in array with size ARRAY_SIZE
// Writes content of the set to the console
for (List<Integer> list2 : set) {
System.out.print("List: ");
for (Integer integer2 : list2) {
System.out.print(" " + integer2 + " ");
}
System.out.println();
}
}
private static void recursion(ArrayList<Integer> notSmallestCombination) {
ArrayList<Integer> listTemp = (ArrayList<Integer>) notSmallestCombination.clone();
for (int i = 0; i < notSmallestCombination.size(); i++) {
listTemp.remove(i);
if (listTemp.size() == SIZE_OF_SUBARRAYS) {
for (int j = 0; j < notSmallestCombination.size(); j++) {
ArrayList<Integer> list2Temp = (ArrayList<Integer>) notSmallestCombination.clone();
list2Temp.remove(j);
set.add(list2Temp);
}
} else {
recursion(listTemp);
}
listTemp = (ArrayList<Integer>) notSmallestCombination.clone();
}
}
}
And result is:
Type the size of the array:
5
Type the size of subarrays:
3
List: 0 3 4
List: 0 2 3
List: 0 1 2
List: 1 3 4
List: 1 2 3
List: 0 2 4
List: 0 1 3
List: 2 3 4
List: 1 2 4
List: 0 1 4
I found something on internet here https://www.geeksforgeeks.org/print-all-possible-combinations-of-r-elements-in-a-given-array-of-size-n/
The code use a permutation function :
// Java program to print all combination of size r in an array of size n
import java.io.*;
class Permutation {
/* arr[] ---> Input Array
data[] ---> Temporary array to store current combination
start & end ---> Staring and Ending indexes in arr[]
index ---> Current index in data[]
r ---> Size of a combination to be printed */
static void combinationUtil(int arr[], int data[], int start,
int end, int index, int r)
{
// Current combination is ready to be printed, print it
if (index == r)
{
for (int j=0; j<r; j++)
System.out.print(data[j]+" ");
System.out.println("");
return;
}
// replace index with all possible elements. The condition
// "end-i+1 >= r-index" makes sure that including one element
// at index will make a combination with remaining elements
// at remaining positions
for (int i=start; i<=end && end-i+1 >= r-index; i++)
{
data[index] = arr[i];
combinationUtil(arr, data, i+1, end, index+1, r);
}
}
// The main function that prints all combinations of size r
// in arr[] of size n. This function mainly uses combinationUtil()
static void printCombination(int arr[], int n, int r)
{
// A temporary array to store all combination one by one
int data[]=new int[r];
// Print all combination using temprary array 'data[]'
combinationUtil(arr, data, 0, n-1, 0, r);
}
/*Driver function to check for above function*/
public static void main (String[] args) {
int arr[] = {1, 2, 3, 4, 5};
int r = 3;
int n = arr.length;
printCombination(arr, n, r);
}
}
/* This code is contributed by Devesh Agrawal */
Once you have all the permutation you just have to build an array with it

How do I use parts of an old array to create a new one in java?

So I need to create a new array that swaps the first and last values of my existing array. Here's what I have so far:
import java.util.Scanner;
import java.util.Arrays;
public class P9_ArrayManipulate
{ public static void main (String[] args)
{ Scanner in = new Scanner(System.in);
System.out.println("Please enter seven numbers for an Array.");
int []array = new int[7];
int total = 0;
for (int i = 0; i < 7;i++){
array[i] = in.nextInt();
}
System.out.println("Your reversed array is "+reverseArray(array));
System.out.println("Your swapped array is "+swapArray(array));
System.out.println("Your array without even numbers is "+evenArray(array));
System.out.println("The program has finished calling array methods.");
}
public static int []reverseArray(int []array)
{ int[] reversed = new int[array.length];
int i;
for(i=0; i < array.length; i++)
{
reversed[i] = array[(array.length - i -1)];
}
return reversed;
}
public static int []swapArray (int []array)
{
array[0] += array[array.length-1];
array[array.length-1] = array[0] - array[array.length-1];
array[0] -= array[array.length-1];
return array;
}
public static int []evenArray(int []array)
{ for (int i = 0; i < array.length;i++){
if (array[i]%2 !=0)
{array[i] = 0;}
i++;}
return array;
}
}
Everything compiles correctly (as far as I can tell), but I'm getting a weird run time error. After seven inputs, I get this as my output:
Your reversed array is [I#b4d079
Your swapped array is [I#3644d1
Your array without even numbers is [I#3644d1
The program has finished calling array methods.
It would be much easier to just swap the first and last values of the array passed in to the swapArray() function and return that instead of creating a new array.
Something like the following will work (and it doesn't create a new variable to facilitate swapping):
public static int[] swapArray(int[] array) {
array[0] += array[array.length-1];
array[array.length-1] = array[0] - array[array.length-1];
array[0] -= array[array.length-1];
return array;
}
You have to import Arrays from java.util.Arrays
You may use the following answer to merge the arrays in swapArray() method
How can I concatenate two arrays in Java?
Try something like this:
*Edit: If its a must to create new array, just create int newarray[] = method(); instead of array[]=method();
import java.util.Scanner;
public class Array
{
public static void main (String[] args)
{ Scanner in = new Scanner(System.in);
System.out.println("Please enter seven numbers for an Array.");
int []array = new int[7];
for (int i = 0; i < 7;i++){
array[i] = in.nextInt();
}
array = reverseArray(array);
System.out.println("Your reversed array is :");
for (int i = 0; i < array.length; i++) {
System.out.print(array[i]+" ");
}
System.out.println();
array = swapArray(array);
System.out.println("Your swapped array is :");
for (int i = 0; i < array.length; i++) {
System.out.print(array[i]+" ");
}
// System.out.println("Your array without even numbers is "+evenArray(array));
System.out.println();
System.out.println("The program has finished calling array methods.");
}
public static int[] reverseArray(int []array)
{ int left = 0;
int right = array.length-1;
while(left<right){
int reverse = array[left];
array[left]=array[right];
array[right] = reverse;
left++;
right--;
}
return array;
}
public static int []swapArray (int []array)
{
int help = 0;
help = array[0];
array[0] = array[6];
array[6] = help;
return array;
}
}

java methods multiplying elements with in an array using a loop

Define a Java method named weightedSum() that takes two integer arrays as its arguments. The
method uses a loop to multiply corresponding elements of the two arrays together (i.e., it multiplies the first argument of each array together, followed by multiplying the second element of each array together, and so on) and returns the sum of those products (which is also an integer). You may assume that both arrays are of equal length.
public int weightedSum(int [] a ,int [] b)
{
int value;
int sum ;
for (int i = 0 ; i < a.length ; i++)
{
value = a[i] * b [i];
value = value +value ;
}
return value;
I am having trouble writing this method out for my assignment . I under stand it accepts to arrays but i am having trouble writing out the loop itself so that it multiplies each individual element of the array with its counterpart in the opposite array so pos [1] * pos [1] and then add the two values togather with pos [2] + pos[2] and to get the sum total for all the values
below are the changes needed in your code. Basically you never updated the variable sum after you compute the product of corresponding elements in the two arrays. Also you might wanna use long type to store the result of the sum & the product as the int value might overflow if the elements in the array are sufficiently large.
public long weightedSum(int [] a ,int [] b)
{
long value = 0;
long sum = 0 ;
for (int i = 0 ; i < a.length ; i++)
{
value = a[i] * b [i];
sum = sum +value ;
}
return sum;
}
Try this:
public long dotProduct(int [] a, int [] b) {
if (a == null) throw new IllegalArgumentException("a array cannot be null");
if (b == null) throw new IllegalArgumentException("b array cannot be null");
if (a.length != b.length) throw new IllegalArgumentException("arrays must have equal lengths");
long sum = 0L;
for (int i = 0; i < a.length; i++) {
sum += a[i]*b[i];
}
return sum;
}
Most of the code looks correct, however the second line in the loop should not be changing the value variable, the sum variable should be updated with the value.
something like sum += value.
then return sum.
import java.util.*;
public class Demo
{
public static void main(String args[])
{
System.out.println("Hello World");
System.out.println("Enter n :");
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
Integer[] arr = new Integer[n];
System.out.println("Enter Elements :");
for(int i=0;i<n;i++)
{
arr[i]=sc.nextInt();
}
//Ascending Array
Arrays.sort(arr);
System.out.println("Elements Are :");
for(int i=0;i<n;i++)
{
System.out.println(arr[i]);
}
//Descending Array
Arrays.sort(arr,Collections.reverseOrder());
System.out.println("Elements Are :");
for(int i=0;i<n;i++)
{
System.out.println(arr[i]);
}
//Product Of First Four Elements Of Array
int product=1;
for(int i=0;i<4;i++)
{
product=product*arr[i];
}
System.out.println("Product : "+product);
}
}
/* Output
Hello World
Enter n :
5
Enter Elements :
4
5
9
8
6
Elements Are :
4
5
6
8
9
Elements Are :
9
8
6
5
4
Product : 2160
*/
import java.util.*;
public class DemoNew
{
public static void main(String args[])
{
System.out.println("Hello World");
System.out.println("Enter N : ");
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
Float[] r = new Float[n];
System.out.println("Enter Distances : ");
for(int i=0;i<n;i++)
{
r[i]=sc.nextFloat();
}
System.out.println("Distances : ");
for(int i=0;i<n;i++)
{
System.out.println(r[i]);
}
for(int i=0;i<r.length;i++)
{
if(r[i] == 0.0)
{
System.out.println("Invalid");
break;
}
else if(r[i] < 0)
{
System.out.println("Invalid");
break;
}
else
{
//Descending Array
Arrays.sort(r,Collections.reverseOrder());
System.out.println("Distances in Descending Order Are :");
for(int j=0;j<n;j++)
{
System.out.println(r[j]);
}
System.out.println("3 Max Distances Are :");
for(int k=0;k<3;k++)
{
System.out.println(r[k]);
}
List<Float> list = Arrays.asList(r);
System.out.println(list);
/* Float[] ar = new Float[r.length];
for(int m=0;m<r.length;m++)
{
ar[m]=r[m];
}
System.out.println("Final Ans :"); */
break;
}
}
}
}
Change to this:
value += a[i] * b [i];
// value = value + value;
Also initialize value to 0 before using it.
Also remove the sum variable.

Categories

Resources