Java: Solving the Arrays Dilemma

  • Context: Comp Sci 
  • Thread starter Thread starter Vintageflow
  • Start date Start date
  • Tags Tags
    Arrays Java
Click For Summary

Discussion Overview

The discussion revolves around a programming assignment focused on arrays in Java, specifically on how to input an array of integers, remove duplicate elements, and implement this functionality through methods. The participants explore various coding approaches, potential issues, and best practices related to the assignment requirements.

Discussion Character

  • Homework-related
  • Technical explanation
  • Debate/contested

Main Points Raised

  • The original poster shares their code and expresses confusion about how to remove duplicate numbers in their second method.
  • Some participants suggest that the second method should not handle input, but rather accept the array as a parameter.
  • There is a discussion about whether a method can return an array in Java, with some participants asserting that it is possible.
  • Concerns are raised regarding the use of class-level variables, with suggestions to declare all variables within methods to comply with assignment requirements.
  • Participants point out specific issues in the original code, such as the incorrect starting index for the input loop and the need to handle potential input errors.
  • One participant proposes a revised structure for the main method and suggests renaming the second method to better reflect its purpose.

Areas of Agreement / Disagreement

Participants generally agree on the need to pass the array to the second method and to avoid using class-level variables. However, there is no consensus on the best approach to implement the duplicate removal functionality, and various coding strategies are discussed.

Contextual Notes

Limitations include the potential for input errors if non-integer values are entered, and the need for clarity on how to manage array sizes and indices correctly.

Who May Find This Useful

Readers interested in Java programming, particularly those working on array manipulation and method implementation in homework or project settings.

Vintageflow
Messages
5
Reaction score
0
hello all, I was given an assignment on arrays, here is the task:

Write a program that inputs an array of 10 integers from the user, and removes the duplicate array elements. You may assume that all the integers are between 0 and 100, and you may input them from the user however you wish. The easiest way to do this is to store only the non-repeating elements (only store a number the first time you see it). Please write at least 1 function in addition to the main method, and pass the array into that function as a parameter. Don't use any class-level variables. Each variable should be declared inside a method. Here is some sample output:
Please enter 10 integers, hitting return after each one:
5
75
10
75
5
80
10
5
5
50
You entered 5 unique numbers:
5 75 10 80 50

here is what my program looks like:

import java.util.Scanner;

public class DeDup
{
static Scanner scan = new Scanner(System.in);

public static void main(String[] args)
{
int[] nums;
int numbers, array;
boolean number;

System.out.print("Please enter 10 integers, hitting return after each one: ");
numbers = scan.nextInt();
nums = new int[10];

for(int count = 1; count < 10; count++)
{
nums[count] = scan.nextInt();
}
}
public static int[] numMethod()
{
int i, j=0, arraySize=10;
int[] inputNum = new int[arraySize];

for (i=0; i<arraySize; i++)
{
inputNum = scan.nextInt();
}

for (i=0; i<arraySize; i++)
{
for(j=0; j<i; j++)
{
if (inputNum == inputNum[j])
inputNum = inputNum[j-1];
j--;
}
}

System.out.print(inputNum+" ");

return(inputNum);

}
}

my first method works fine (inputing the 10 numbers using an array), but I'm having trouble on the second method, where I get rid of the duplicate numbers and only display the unique numbers. How do you get rid of the duplicates? Is the second method even right?

thank you all for the help!
 
Physics news on Phys.org
I added [ code] and [ /code] tags, without the leading spaces, around your code.
Vintageflow said:
hello all, I was given an assignment on arrays, here is the task:

Write a program that inputs an array of 10 integers from the user, and removes the duplicate array elements. You may assume that all the integers are between 0 and 100, and you may input them from the user however you wish. The easiest way to do this is to store only the non-repeating elements (only store a number the first time you see it). Please write at least 1 function in addition to the main method, and pass the array into that function as a parameter. Don't use any class-level variables. Each variable should be declared inside a method. Here is some sample output:
Please enter 10 integers, hitting return after each one:
5
75
10
75
5
80
10
5
5
50
You entered 5 unique numbers:
5 75 10 80 50

here is what my program looks like:
Code:
import java.util.Scanner;

public class DeDup
{
 static Scanner scan = new Scanner(System.in);
 
  public static void main(String[] args)
  {
  	 int[] nums;
	 int numbers, array;
	 boolean number;
	 
	 System.out.print("Please enter 10 integers, hitting return after each one: ");
	 numbers = scan.nextInt();
	 nums = new int[10];
	 
	 for(int count = 1; count < 10; count++)
	 {
	 	nums[count] = scan.nextInt();
	 }
  } 
  public static int[] numMethod()
  {
   int i, j=0, arraySize=10;
   int[] inputNum = new int[arraySize];
               
   for (i=0; i<arraySize; i++)
   {
     inputNum[i] = scan.nextInt();
   }
               
   for (i=0; i<arraySize; i++)
   {
	  for(j=0; j<i; j++)
	  {	
		if (inputNum[i] == inputNum[j])
        inputNum[i] = inputNum[j-1];
		  j--;  
     }                  
   }

     System.out.print(inputNum[i]+" ");
     
	  return(inputNum);

  }
}
my first method works fine (inputing the 10 numbers using an array), but I'm having trouble on the second method, where I get rid of the duplicate numbers and only display the unique numbers. How do you get rid of the duplicates? Is the second method even right?

thank you all for the help!
 
Your second function should not be doing input - you already have done the input in your Main method, so there is no reason for your numMethod to ask for them to be input again. Instead, pass the array as a parameter to your numMethod method.

I'm a little rusty with Java, so don't remember if a function can return an array type. You can't do this in C or C++, but possibly you can in Java.

If this is allowed, have your numMethod (which BTW is not a useful name) return a different array with the duplicates removed. If returning an array is not allowed, write the numMethod method with two parameters, one of which represents the input array and the other, the array with duplicates removed.
 
Thank you for the reply Mark44 :)

One more question, if you remember, do you know how to remove an element in arrays?
 
Vintageflow,

Yes, you can pass an array to a method. There are a number of problems with what you've written though.

Your assignment has the following instructions:

1. Write a program that inputs an array of 10 integers from the user, and removes the duplicate array elements.
2. You may assume that all the integers are between 0 and 100, and you may input them from the user however you wish. The easiest way to do this is to store only the non-repeating elements (only store a number the first time you see it).
3. Please write at least 1 function in addition to the main method, and pass the array into that function as a parameter.
4. Don't use any class-level variables. Each variable should be declared inside a method.

Here are some of the problems that I've found.
1. scan is a class-level variable. (violates #4 of your requirements)
2. the int array and boolean number variables in the main method are not being used by anything. Same for the j=0 in the numMethod().
3. The first scan.nextInt() call puts its number into the numbers variable and doesn't do anything with it.
4. The nums[] array doesn't put anything into its first position. Your for loop should start with int count = 0;
5. The numMethod() method doesn't take an array as required, it returns one. The method also isn't being called by anything. Your program never leaves the main method. (#3 of your requirements)
6. If the user types something other than a number, the program throws an error and ends. You should always catch basic errors like this.

I'll give you the shell of the main method and another method. Mark is right on the naming thing so let's change that to a method called checkNumber. Keep in mind that the position of the first array is 0. Therefore, int[] nums = new int[1] is an array of size one but the data is entered in the num[0] position. You can use this to your advantage in the checknumber method.

Code:
import java.util.Scanner;

public class DeDup {

    public static void main(String[] args) {
        // I'm setting this to zero for now.  There is a reason for this...
        int[] nums = new int[0];
        Scanner scan = new Scanner(System.in);

        System.out.println("Please enter 10 integers, hitting return after each one: ");

        for (int count = 0; count < 10; count++) {
            try {
                nums = checkNumber(scan.nextInt(), nums);
            } catch (Exception e) {
                // If the user typed something other than a number, what should the program do?

            }
        }

        System.out.println("You entered " + nums.length + " unique numbers:");
        // Write something to display the numbers
		
    }

    private static int[] checkNumber(int number, int[] nums){
        // newNums is always an array that is one larger than nums
        int[] newNums = new int[nums.length+1];
        for(int i = 0; i < nums.length; i++){
            // What do you want to do if you find a match?
            if(number == nums[i]){
                // Hint, you want to return something

            }
            // Add to the new array
            newNums[i]=nums[i];
        }
        // If you got here without finding a match, what do you want to do with the number?

        return newNums;
    }
}
 
Borg, here is my attempt to the answer to the questions you left in the program:

// If the user typed something other than a number, what should the program do?
- an if statement, saying that a word or character can not be used.

// What do you want to do if you find a match?
- remove it? If it is, I do not know how to remove an element in an array.

// Hint, you want to return something
- you want to return the numbers that are NOT going to be displayed?

// If you got here without finding a match, what do you want to do with the number?
- you want to display those numbers in your main method.

If these questions are wrong I'm sorry, arrays are confusing to me. :/
 
Vintageflow said:
Borg, here is my attempt to the answer to the questions you left in the program:

// If the user typed something other than a number, what should the program do?
- an if statement, saying that a word or character can not be used.
Yes but, it doesn't need an if statement. Also, do you need to do something with count if an error occurs?
Vintageflow said:
// What do you want to do if you find a match?
- remove it? If it is, I do not know how to remove an element in an array.
// Hint, you want to return something
- you want to return the numbers that are NOT going to be displayed?
Let's ignore the if(number == nums) statement for now. What is this method doing? Let's say that the incoming array (nums) has six numbers in it. At the beginning, we made newNums able to hold 7 numbers (nums.length+1).
In the loop we are copying numbers from nums and putting them into newNums one at a time. When the loop finishes, you will have two arrays - one that has the original numbers (nums) and one that has the originals plus a final place for the new number (newNums). You don't have to remove anything - just choose which one you want to return.
Vintageflow said:
// If you got here without finding a match, what do you want to do with the number?
- you want to display those numbers in your main method.
Has the new number been put into newNums yet? The for loop above is only copying values from nums (which doesn't have the new number in it).
Vintageflow said:
If these questions are wrong I'm sorry, arrays are confusing to me. :/
Not a problem. We're here to help.
 
Last edited:

Similar threads

  • · Replies 7 ·
Replies
7
Views
2K
  • · Replies 7 ·
Replies
7
Views
3K
  • · Replies 21 ·
Replies
21
Views
3K
  • · Replies 18 ·
Replies
18
Views
3K
  • · Replies 2 ·
Replies
2
Views
2K
  • · Replies 5 ·
Replies
5
Views
3K
  • · Replies 5 ·
Replies
5
Views
2K
  • · Replies 17 ·
Replies
17
Views
3K
  • · Replies 12 ·
Replies
12
Views
2K
  • · Replies 3 ·
Replies
3
Views
2K