1 Replies - 266 Views - Last Post: 05 February 2013 - 07:53 PM Rate Topic: -----

#1 ulebarty72  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 2
  • Joined: 05-February 13

Problem Print Distinct Number

Posted 05 February 2013 - 07:36 PM

Hi
I'm having a problem printing the distinct numbers. after i enter 10 numbers it won't print the distinct numbers instead, it would exit the program right away.Here is my code.

[import java.util.Scanner;

public class problem1 {
public static void main(String[] args) {
// numbers array will store distinct values, maximum is 10
int[] numbers = new int[10];

// how many distinct number are in the array
int numberOfDistinctValues = 0;
Scanner input = new Scanner(System.in);
System.out.print("Enter ten numbers: ");

for (int i = 0; i < numbers.length; i++) {
// read an input
int value = input.nextInt();
int j = 0;
for (; j < numberOfDistinctValues; j++) {
if (numbers[j] == value) {
break;
}
}
if (j == numberOfDistinctValues) {
numbers[numberOfDistinctValues] = value;
numberOfDistinctValues++;
}
}

System.out.println("The number of distinct values is " + numberOfDistinctValues);
for (int i = 0; i < numberOfDistinctValues; i++)
System.out.print(numbers[i] + " ");
}
}]

Is This A Good Question/Topic? 0
  • +

Replies To: Problem Print Distinct Number

#2 andrewsw  Icon User is offline

  • Fire giant boob nipple gun!
  • member icon

Reputation: 2891
  • View blog
  • Posts: 9,599
  • Joined: 12-December 12

Re: Problem Print Distinct Number

Posted 05 February 2013 - 07:53 PM

It works for me. Depending on where you are running it from, you need to pause the console, otherwise it will just exit when the code finishes.

try {
    System.in.read();
} catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}

This is one way, and there is quite a lot of discussion on the internet about this particular topic.
Was This Post Helpful? 1
  • +
  • -

Page 1 of 1