hii every body
how are you?
in fact, i am a beginner in java programming and i do my best to improve myself in this language so i tried to solve many exercises to confirm that i have no difficulty with this language. I solved this question but i had doubt that there is logic error.therefore, i hope you check the codes and lead me to the right way.The question is:

How can i write a program that reads in ten numbers and displays distinct numbers (i.e if a number appears multiple times, it is displayed only once. Hint: Read a number and store it to an array if it is new. If the number is already in the array, discard it (i.e store a zero in its place). After the input, the array contains the distinct numbers. This should be done in the main() method?

And how can i write another method called disArray() that expects an array (i.e the array that you just created) and return nothing. It displays the contents of this array to the user?

the codes here :

import java.util.Scanner;
public class Array {
  public static void main(String [] args) {
    Scanner con = new Scanner(System.in);
    int [] numbers = new int [10];
  for( int i = 0; i < numbers.length; i++)
  {
    System.out.print("enter a number:");
    numbers [i] =con.nextInt();
 
}
  int nothing = divArry (numbers);
  
  System.out.println(" the number is"+ nothing);
  }
  public static int divArry( int numbers []){
    int nothing = 0;
  
  for ( int i = 0; i<numbers.length; i++)
    
  {
    nothing += numbers[i];
  }
  return nothing;
  }

Recommended Answers

All 6 Replies

Hello, hypocrisy.
For keeping distinct numbers, you can use, for example Class ArrayList<E>. This class contains method to check, if the list already contains given element.

thanks ,dear for these really precious information about array

Also, you have interesting name for variable, that keep returning value ('nothing'). If you want return nothing from method, you should use void keyword.
For your code it's:

public static int divArry( int numbers [])

turns into

public static void divArry( int numbers [])

And print information directly from your method :)

Or specify more proper name for that variable.
P.S. It's not obligatory, but I think that can make your code better :)

thanks, dear again

it seems nobody has clue about the codes and the question that i have asked

Simply use a Set (i.e. HashSet). That doesn't allow you to add duplicate entries, but doesn't through an exception if it is a duplicate (the method to add simply returns false if the entry already exists).

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.