This is the question I was given: Write a program that reads in ten numbers and
ID: 3626888 • Letter: T
Question
This is the question I was given: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. After the input, the array contains the distinct numbers.)
I can't get my program to weed out the repeat numbers. Please help.
This is what I have:
import java.util.Scanner;
public class distinctNumbers
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
int[] nums = new int[10];
int num = 0;
for(int i = 0; i < nums.length; i++)
{
System.out.println("Enter number " + (i+1) + ": ");
int newN = input.nextInt();
nums[i] = newN;
boolean isInArray = false;
for(int j = 0; j < num; j++)
{
if(newN == nums[j])
isInArray = true;
break;
}
}
for(int i = 0; i < nums.length; i++)
{
System.out.println(nums[i]);
}
}
}
Explanation / Answer
import java.util.Scanner;
public class distinctNumbers
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
int[] nums = new int[10];
int num = 0;
for(int i = 0; i < nums.length; i++)
{
System.out.println("Enter number " + (i+1) + ": ");
int newN = input.nextInt();
boolean notfound=true;
for(int j = 0; j < num; j++)
{
if(newN == nums[j])
{
notfound = false;
break;
}
}
if(notfound)
{
nums[num] = newN;
num++;
}
}
for(int i = 0; i < num; i++)
{
System.out.println(nums[i]);
}
}
}
// fully tested Enjoy.
Related Questions
Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.