printing distinct numbers java - java

I am having a hard time with this code. The code is finished but the output is wrong.
My code prints Enter ten numbers: 1 2 3 5 6 6 8 7 4 1
It should print
The distinct numbers are:
1 2 3 5 6 8 7 4
but it doesn't. It prints:
10 10 10 10 10 7
How can I fix it?
Here is my code:
import java.util.*;
public class homework1 {
public static void main(String[] args){
// input from user
Scanner input = new Scanner(System.in);
int [] numbers = new int[10];
boolean[] distinct = new boolean[10];
System.out.println("Enter ten numbers");
for (int i=0; i<numbers.length; i++){
System.out.println("Number " + (i + 1) +": ");
numbers [i] = input.nextInt();
distinct[i] = true;
for(int j = 0;j<10; j++){
if(numbers[i] == numbers[j] && i != j) {
distinct[i] = false;
}
}
}
int count=0;
for(int j = 0;j<10; j++){
if (distinct[j]){
numbers[count]=distinct.length;
count++;
}
}
System.out.println("The number of distinct number is: "+numbers[count]);
System.out.println("The distinct numbers are: ");
for(int i= 0; i < 10; i++) {
if(distinct[i]) {
System.out.print(numbers[i] + " ");
}
}
System.out.println();
}
}

This line:
numbers[count]=distinct.length;
Is setting your outputs to be the length of the array (Which in this case is hard coded to 10. Try:
int count=0;
for(int j = 0;j<10; j++){
if (distinct[j]){
numbers[count]=numbers[j];
count++;
}
}
Which will set your output to be the distinct number.
Plug: Check out Code Review

This will solve your problem.
If you use HashMap, you will have less code.
import java.util.HashMap;
import java.util.Iterator;
import java.util.Scanner;
import java.util.Set;
public class Test {
public static void main(String[] args) {
HashMap<Integer, String> distinctNumbers = new HashMap<Integer, String>();
// input from user
Scanner input = new Scanner(System.in);
System.out.println("Enter ten numbers");
for (int i = 0; i < 10; i++) {
System.out.println("Number " + (i + 1) + ": ");
Integer numberEntered = input.nextInt();
distinctNumbers.put(numberEntered, null);
}
System.out.println("The number of distinct number is: " + distinctNumbers.size());
System.out.println("The distinct numbers are: ");
Set<Integer> keys = distinctNumbers.keySet();
for (Iterator<Integer> iterator = keys.iterator(); iterator.hasNext();) {
Integer integer = (Integer) iterator.next();
System.out.print(" "+ integer);
}
}
}

Remove line numbers[count] = distinct.length; This make your output are all 10
Then, I change your code a little to make it run right:
...
int count = 0;
for (int j = 0; j < 10; j++) {
if (distinct[j]) {
//numbers[count] = distinct.length; //remove it, it nonsense
count++;
}
}
// distinct number should be count, not number[count]
System.out.println("The number of distinct number is: " + count);
....

public static void main(String[] args) {
int arr[] = {1,3,5,4,7,3,4,7};
Map<Integer, Integer> frequency = new HashMap<Integer, Integer>();
for(int i = 0; i < arr.length; i++) {
if(frequency.containsKey(arr[i])){
int value = frequency.get(arr[i]);
frequency.put(arr[i], value + 1);
}
else {
frequency.put(arr[i], 1);
}
}
for(Map.Entry<Integer, Integer> entry : frequency.entrySet()) {
System.out.println(entry.getKey());
}
}

package Chapter7;
import java.util.Scanner;
public class Exercise7_5 {
public static void main(String[] args) {
// Print distinct numbers
Scanner input = new Scanner(System.in);
int[] numbers = new int[10];
System.out.println("Enter 10 numbers: ");
for (int i = 0, j = 0; i < 10; i++) {
if (storeDistinctNumbers(j,input.nextInt(), numbers))
j++;
}
for (int i = 0; numbers[i] != 0 ; i++)
System.out.print(numbers[i] + " ");
}
public static boolean storeDistinctNumbers(int j, int num, int[] numbers) {
for (int e: numbers) {
if (e == num)
return false;
}
numbers[j] = num;
return true;
}
}

Related

IDK why my code keeps crashing taking the input only one time in this loop

The question is taking input of names of students and their score and declaring the topper but the output ain't working.
Here, I am looking for the highest mark with always keeping the value of the current highest mark, please help me if I am missing something.
import java.util. * ;
public class Topper {
public static void main(String args[]) {
Scanner sc = new Scanner(System. in );
String studentTemp = "";
String students[] = new String[100];
int i = 0,
j = 0,
temp = 0,
n = 0;
int score[] = new int[100];
do {
System.out.println("Enter the Name");
students[i] = sc.nextLine();
System.out.println("Enter the Score");
score[i] = sc.nextInt();
n++;
i++;
} while ( students [ i ] != "Alldone");
for (i = 0; i < n; i++) {
for (j = i + 1; j < n - 1; j++) {
if (score[j] > score[i]) {
temp = score[j];
score[j] = score[i];
score[i] = temp;
studentTemp = students[i];
students[i] = students[j];
students[j] = studentTemp;
}
}
}
System.out.println("The Student with Highest score : " + students[n - 1] + " with score : " + score[n - 1]);
System.out.println("The Students performance list : ");
for (i = n - 1; i >= 0; i++)
System.out.println(students[i] + " " + score[i]);
}
}
Try this
import java.util.*;
public class Topper
{
public static void main(String args[]) {
Scanner sc=new Scanner(System.in);
String studentTemp="";
String students[]=new String[100];
int i=0,j=0,temp=0,n=0,stop=0;
int score[]=new int[100];
do
{
System.out.println("Enter the Name");
students[i]=sc.next();
System.out.println("Enter the Score");
score[i]=sc.nextInt();
System.out.println("Do you wish to continue \n Press 0 to continue \n Press 1 to exit");
stop=sc.nextInt();
n++;
i++;
}
while(stop!=1);
temp=score[0];
studentTemp=students[0];
for(i=1;i<n;i++)
{
if(score[i]>temp)
{
temp=score[i];
studentTemp=students[i];
}
}
System.out.println("The Student with Highest score : "+ studentTemp +" with score : "+temp);
System.out.println("The Students performance list : ");
for(i=0;i<n;i++)
System.out.println(students[i]+" "+score[i]);
}
}```

I am unable to delete elements from within my array when i ask for user input

When i ask the user to input a number to delete from the array it simply puts out 0 and than asks to try again i want the number to be deleted completely until the array is empty here is the code i have so far:
import java.util.Scanner;
import java.util.Random;
public class DeleteElements
{
public static void main(String[]args)
{
Scanner keyboard = new Scanner(System.in);
int arr[] = new int[20];
int num, found = 0,
arrSize = 10;
String choice;
Random randomGenerator = new Random();
for (int i = 0; i<10; i++)
{
arr[i] = randomGenerator.nextInt(100);
}
for(int i = 0; i<10; i++)
{
System.out.print("" + arr[i] + " ");
}
do
{
System.out.print("Number to Delete: ");
num = Integer.parseInt(keyboard.nextLine());
if(arrSize <=0)
{
System.out.println("The array is now empty");
break;
}
else
{
for (int i = 0; i<10; i++)
{
if(arr[i] == num)
{
found = 1;
}
if (found == 1)
arr[i] = arr[i + 1];
}
if (found == 0)
System.out.println("Number not found,");
else
{
arrSize--;
int i = 0;
for ( i = 0; i <arrSize; i++);
{
System.out.print("" + arr[i] + " ");
}
found = 0;
}
System.out.println(" Try again (y/n) ? ");
choice = keyboard.nextLine();
}
}while (choice.charAt(0) == 'y' || choice.charAt(0) == 'Y');
}
}
i want it to look something like this:
Array: 3, 63, 45
Delete NUmber: "User inputs 45"
Array: 3, 63
Issue is here:
for ( i = 0; i <arrSize; i++);
You have a semicolon after for loop. Remove that and your code works as expected.

Comparing an element of an array to an integer

Here is my assignment:
create an array of N random integers in the range of 1 to 100 (you can use the Java random class for this). Get the value of N from the user. Next ask the user to input a number in this range (1 to 100) and then search the array to locate all occurrences of the search number. For each occurrence, print out the number and the position at which it was found.
Then sort the array and search again, displaying all occurrences of the search number. If the search number is not found, then display a message to that effect.
Finally, print the sum of all of the numbers in the array.
I cannot figure out to how compare elements of the array to an integer. Please help! Here is what I have so far
public class Array {
public static void main(String[] args)
{
int num;
int searchNum;
int position = 0;
Scanner in= new Scanner(System.in);
System.out.println("How many random integers you want to create in range (1, 100)");
num = in.nextInt();
int[] myList = new int[num];
for (int i = 0; i < num; i++)
{
Random r = new Random();
int j = r.nextInt(101);
myList[i] = j;
}
System.out.println("Enter a number from 1-100 to search");
searchNum = in.nextInt();
for (int i = 0; i < num; i++)
{
if (searchNum == myList[i])
{
System.out.println(searchNum + " found at location: " + (position+1));
}
else
{
position += 1;
}
}
}
}
System.out.println("Enter a number from 1-100 to search");
searchNum = in.nextInt();
for (int i = 0; i < num; i++)
if (searchNum == myList[i])
System.out.println(searchNum + " found at location: " + (i+1));
You was nearly done, I believe.
public class Array {
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
System.out.println("How many random integers you want to create in range (1, 100)");
final int num = in.nextInt();
int[] myList = new int[num];
Random r = new Random();
for (int i = 0; i < num; i++)
{
myList[i] = r.nextInt(101);
}
System.out.println("Enter a number from 1-100 to search");
final int searchNum = in.nextInt();
for (int i = 0; i < num; i++)
{
if (searchNum == myList[i])
{
System.out.println(searchNum + " found at location: " + i);
}
}
Arrays.sort(myList);
boolean any = false;
for (int i = 0; i < num; i++)
{
if (searchNum == myList[i])
{
System.out.println(searchNum + " found ");
any = true;
}
else if (searchNum > myList[i])
{
break;
}
}
if (!any)
{
System.out.println("the search number is not found");
}
}
}

how to display the position of array

Your program should display whether the inputted integer value is found in list, how many of it is in list, and what are their locations in list?
sample
List : 1 3 2 5 7 8 5 6 9 4
Input value to search in List: 9
The value 9 is in List!
There are 4 of it in List.
Located at: list[4], list[5], list[6], list[8]
this is my code
import java.io.*;
public class List{
public static void main(String[] args){
int list[] = new int[10];
int i, num = 0, num1=0;
String input = " ";
BufferedReader in = new BufferedReader(new
InputStreamReader(System.in));
for(i = 0; i < 10; i++){
list[i] = 0;
}
for(i = 0; i < 10; i++){
System.out.print("Input value for list[" + i + "] = ");
try{
input = in.readLine();
num = Integer.parseInt(input);
list[i] = num;
for(i = 0; i < 10; i++){
System.out.println("list[" + i + "] = " +list[i]);
}
for (int b = 0; b < list.length; ++b) {
if (num1 == list[b]) {
returnvalue = b;
break;
}
}
System.out.print("Input value for list");
input = in.readLine();
num1 = Integer.parseInt(input);
}catch(IOException e){}
System.out.println("the position is" + returnvalue);
}
}
}
I think the position that is returning is not accurate can you help me?
This will do what you want... Modify the System.out.println(); part according to your need.
public static void main(String[] args) throws IOException {
int list[] = new int[10];
int i, num = 0, num1 = 0;
int returnvalue = 0;
String input = " ";
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
for (i = 0; i < 10; i++) {
list[i] = 0;
}
for (i = 0; i < 10; i++) {
System.out.print("Input value for list[" + i + "] = ");
input = in.readLine();
num = Integer.parseInt(input);
list[i] = num;
}
for (i = 0; i < 10; i++) {
System.out.println("list[" + i + "] = " + list[i]);
}
System.out.print("Input value for checking in list ");
input = in.readLine();
num1 = Integer.parseInt(input);
boolean flag = false;
int[] arr = new int[10];
int count= 0;
for (int b = 0; b < list.length; ++b) {
if (num1 == list[b]) {
flag = true;
arr[count]=b;
count++;
}
}
if(flag)
{
System.out.println("The value "+num1+" is in List!");
System.out.println("There are "+count+" of it in List");
System.out.print("Located at: ");
for(int j=0; j<count;j++)
{
System.out.print(" List["+arr[j]+"]");
}
}
else {
System.out.print(" Element Not found");
}
}
The Console Part for input output is...
Input value for list[0] = 4
Input value for list[1] = 5
Input value for list[2] = 6
Input value for list[3] = 4
Input value for list[4] = 5
Input value for list[5] = 6
Input value for list[6] = 5
Input value for list[7] = 4
Input value for list[8] = 4
Input value for list[9] = 6
list[0] = 4
list[1] = 5
list[2] = 6
list[3] = 4
list[4] = 5
list[5] = 6
list[6] = 5
list[7] = 4
list[8] = 4
list[9] = 6
Input value for checking in list 4
The value 4 is in List!
There are 4 of it in List.
Located at:List[0] List[3] List[7] List[8]
Fixes in your code
A try block is either with a catch block or with a finally block or both.
Having two same variables in inner and outer loop is not good. In your case the outer loop will iterate just once. I think which is not needed.
There are two nested for loop where the loop control variable is same:
for(i = 0; i < 10; i++){
System.out.print("Input value for list[" + i + "] = ");
...
for(i = 0; i < 10; i++){
System.out.println("list[" + i + "] = " +list[i]);
}
...
So, the outer for loop will never iterate what you are expecting. Use a different loop control variable for the inside for loop.
here is my solution for your problem. no need to use that much of loops. you want to use only one foreach - How does the Java 'for each' loop work? (if you don't need to ask question again and agian). I was unable to test this lot :). But, I hope this will work.
import java.util.*;
class MyList{
public static void main(String arga[]){
int array[] = {1,3,2,5,7,8,5,6,9,4};
Scanner input = new Scanner(System.in);
// recursively ask the question
while(true){
System.out.print("Enter the value to search in list: ");
int value = input.nextInt();
System.out.println();
int i = 0;// to get the array index
int count = 0; // to get how many
String list = "Located at: ";
boolean isTrue = false; // to get entered value is in the list or not
for(int a: array){
if(a == value){
isTrue = true;
list += "list[" + i + "],";
count++;
}
i++;
}
if(isTrue){
//remove the last "," from the string
list = list.substring(0, list.length() - 1);
System.out.println("The value " + value +" is in List!");
System.out.println("There are " + count +" of it in List.");
System.out.println(list);
}else{
System.out.println("this value is not in the list");
}
}
}
}

java array searching method

I have to make an array whose 10 numbers are chosen by the user through a scanner. The program orders the 10 numbers in ascending order, then prints out the new list. Then It asks the user to enter any number and then uses a binary search to see if the number is in the list of 10 numbers.
Here is what I have so far:
import java.util.Scanner;
public class lab11 {
public static void main(String[] args){
double[] numbers = new double[10];
System.out.println("Please enter 10 double values:");
for (int i=0;i<10;i++){
numbers[i] = inputArray();
}
System.out.println("sorting");
print(selectionSort(numbers));
System.out.println("Please enter a search key:");
}
public static double inputArray(){
Scanner input = new Scanner(System.in);
System.out.print(">");
double d = input.nextInt();
return d;
}
public static double[] selectionSort(double[] list){
double temp;
for(int i=0; i < (list.length-1); i++){
for(int j = i+1; j < list.length; j++){
if(list[j] < list[i]){
temp = list[i];
list[i] = list[j];
list[j] = temp;
}
}
}
return list;
}
public static void print(double[] arr){
for(double d:arr){
System.out.println("list["+j+"]"+" = "+d);
}
}
public static int binarySearch(double[]list, double key){
int low=0,high=list.length -1;
key =input.nextInt();
while(high>=low){
int mid=(low+high)/2;
if(key<list[mid])
high=mid-1;
else if(key==list[mid]) return mid;
else low=mid+1;
}
return-1;
}
}
I need help with 2 things.
(1) is under the Print method. I want the program to print out like "list[i] = d" The d a number that the user puts in and it works fine, but the i doesn't. I want it to be the array number which is 0 through 9.
(2) I need help with invoking the binary search so I can have an output for the search.
Just for the right input, you can write a do...while loop, which loops till the input is valid:
for (int i = 0; i < 10; i++) {
double number;
Scanner input = new Scanner(System.in);
do {
System.out.print(">");
number = input.nextDouble();
} while (number < 0 || number > 10);
}
}
For the output you seem to want use
// [...] perform the sorting [...]
// enter the search key
System.out.println("Please enter a search key:");
final int position = Arrays.binarySearch(numbers, input.nextDouble());
if (position < 0) {
System.out.println("key is not in the list");
} else {
System.out.println("key is at position " + position);
}
I would write like this
public static void main(String[] args) {
// initialize
double[] numbers = new double[10];
Scanner input = new Scanner(System.in);
// insert variables into array
inputArray(numbers, input);
// start sorting
System.out.println("sorting");
selectionSort(numbers);
// print the sorted array
print(numbers);
// binary search
binarySearch(numbers, input);
// close scanner
input.close();
}
public static void inputArray(double[] numbers, Scanner input) {
System.out.println("Please enter 10 double values:");
for (int i = 0; i < 10; i++) {
System.out.print(">");
numbers[i] = input.nextDouble();
}
}
public static void print(double[] numbers) {
for (int i = 0; i < numbers.length; i++) {
System.out.println("list[" + i + "]" + " = " + numbers[i]);
}
}
public static double[] selectionSort(double[] list) {
double temp;
for (int i = 0; i < (list.length - 1); i++) {
for (int j = i + 1; j < list.length; j++) {
if (list[j] < list[i]) {
temp = list[i];
list[i] = list[j];
list[j] = temp;
}
}
}
return list;
}
public static void binarySearch(double[] numbers, Scanner input) {
System.out.println("Please enter a search key:");
double key = input.nextDouble();
int index = Arrays.binarySearch(numbers, key);
if (index < 0) {
System.out.println(key + " is not in the list");
} else {
System.out.println(key + " is in the list, index = " + index);
}
}

Categories

Resources