Returning arrays to main method - java

I have a question about returning an array from one method back to main. It is seriously starting to annoy me and I cannot wrap my brain around this. It seems as if even though I have changed the array in my method, when I go to display it in main it displays the old array. I'm trying to remove the duplicate numbers in my array and I know it works because I have stepped through it in the debugger yet after I return it and go back to main, it displays the whole array again! I know it must be something easy that I am missing here. Can someone please point me in the right direction? Here is my code...
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int[] numbers = new int[10];
System.out.print("Enter 10 numbers: ");
for (int x = 0; x < numbers.length; ++x)
numbers[x] = input.nextInt();
eliminateDuplicates(numbers);
for (int y = 0; y < numbers.length; ++y)
System.out.print(numbers[y] + " ");
}
public static int[] eliminateDuplicates(int[] numbers) {
int[] temp = new int[numbers.length];
int size = 0;
boolean found = false;
for (int x = 0; x < numbers.length; ++x) {
for (int y = 0; y < temp.length && !found; ++y) {
if (numbers[x] == temp[y])
found = true;
}
if (!found) {
temp[size] = numbers[x];
size++;
}
found = false;
}
int[] result = new int[size];
for (int z = 0; z < result.length; ++z)
result[z] = temp[z];
return result;
}
}

Look at this call:
eliminateDuplicates(numbers);
You're ignoring the return value. Perhaps you wanted:
numbers = eliminateDuplicates(numbers);
I sometimes wish that Java had a way of indicating that a method's return value shouldn't be ignored. It would save a lot of questions around InputStream.read as well...

It should be: numbers = eliminateDuplicates(numbers);
You were essentially ignoring the returned result from the method.

Do like this:
int[] result =eliminateDuplicates(numbers);
for (int y = 0; y < result.length; ++y)
System.out.print(numbers[y] + " ");
Also, In your eliminateDuplicates() method, use result array directly by removing temp array. Or rename temp to result and return it. Following code is unnecessary :
int[] result = new int[size];
for (int z = 0; z < result.length; ++z)
result[z] = temp[z];

In Java, parameters are passed by value, so you can't use numbers as an in/out parameter.
e.g. if you C# you could have done
eliminateDuplicates(ref numbers);
But as others have pointed out, the most obvious issue is that you forgot to assign the result :)

In your main, try this:
numbers = eliminateDuplicates(numbers);

Method calling should be like this -
numbers = eliminateDuplicates(numbers);
You are not catching the result returning by eliminateDuplicates function.

Related

How to accept integers into 2 different int arrays simultaneously and form a new array in java in the same order?

If you are accepting integers simultaneously one after another for a different array each time an int is accepted, then how do you form a third array with the digits of the 2 other arrays in the order in which they are accepted?
import java.util.Scanner;
class Integer_Acceptor
{
public static void main()
{
System.out.println("\f");
Scanner sc = new Scanner(System.in);
int a[] = new int[5];
int b[] = new int[10];
int c[] = new int[10];
System.out.println("Enter an integer into each array simultaneously");
for (int i = 0; i < 5; i++)
{
a[i] = sc.nextInt();
b[i] = sc.nextInt();
}
for (int i = 0; i < 10; i++)
{
if (i%2 != 0)
{
c[i] = a[i];
c[i+1] = b[i];
}
}
System.out.println("Array contents are");
for (int i = 0; i < 10; i++)
{
System.out.println(c[i]+"\t");
}
}
}
This is the program I made but obviously it doesn't work (ArrayOutofBounds) as the integer in array increases by 2 every time. How do I make this program give the combined integers of both arrays in the order in which they are accepted?
The idea of separating the inputs is interesting, but it seems to be giving you more problems than solutions when trying to join them together later.
Why not just accept everything into a single array, and when reading it, you test its index to see where it should go? If you have two possible uses for your numbers, odd and even positions will get you there; if three, multiples of 3 plus or minus one, and so on.
This seems to be a simpler solution, and both the input and data storage are as straightforward as can be.
The code you provided will give an ArrayOutofBounds error as you mentioned because c[10] does not exist. (In the second for loop when i = 9, you will be trying to set c[10] which does not exist).
From what I understand, you want array c to contain the following elements:
c = { a[0], b[0], a[1], b[1], a[2], b[2], a[3], b[3], a[4], b[4] }
What I did was to create two separate indices that will help navigate through array a and array b and set c[i] according to whether i was even or odd and then incrementing the respective aIndex or bIndex. I wrote this code below that works the way I described
System.out.println("\f");
Scanner sc = new Scanner(System.in);
int a[] = new int[5];
int b[] = new int[10];
int c[] = new int[10];
System.out.println("Enter an integer into each array simultaneously");
for (int i = 0; i < 5; i++)
{
a[i] = sc.nextInt();
b[i] = sc.nextInt();
}
// Fixed code snipped
int aIndex = 0;
int bIndex = 0;
for (int i = 0; i < 10; i++)
{
// even index
if(i%2 == 0){
c[i] = a[aIndex];
aIndex++;
}
else
{
c[i] = b[bIndex];
bIndex++;
}
}
////
System.out.println("Array contents are");
for (int i = 0; i < 10; i++)
{
System.out.println(c[i]+"\t");
}
Let me know if you need further clarification on how this works so I can edit in a more in-depth explanation.

An array that outputs number 1-5 in random, 1-5 must be output only 2 times without repeating

The code does output 1 - 5 but is there a way to make each number print only twice. (from 1-5 only)
Sample Output,
It does change and is random but outputs more than twice
public class Main {
public static void main(String[] args) {
int num;
int[] random = new int[5]; //this code generates numbers 1–5
int[] array = new int[11]; //array size
for(int x = 0; x < random.length; x++)
random[x] = x; //store the index as a value
for(int x = 0; x < random.length; x++) {
num = (int)(Math.random()*5);
while(random[num] == -1)
num = (int)(Math.random()*5);
if(random[num] != -1)
array[x] = random[num];
random[num] = -1;
}
for(int x = 0; x < array.length; x++)
array[x] = array[x] + 1;
for(int x = 1; x < array.length; x++)
System.out.println("A["+x+"]: "+ array[x]);
}
}
What's the purpose of the random array? It just complicates things. Instead, generate a random number, and check if it is already used twice. If yes, generate another one, if no put it into the array. Repeat until the array is full. Another approach would be to initialize the array with 2 copies of the numbers 1-5 and to do a random permutation.
Just create a variable that records the random records then inside the method or function use if else statement to check the random recorded value to the current value then set up again a variable that provides the limitation to your code.

How do I print nested ArrayLists?

My fourth for loop, for (int y), keeps printing the first m elements over and over again, how can i fix it so that it prints m elements at a time but not the same ones?
Scanner input = new Scanner(System.in);
int n = input.nextInt();
int m = input.nextInt();
ArrayList<String> myname = new ArrayList<String>(n);
ArrayList<Integer> myscore = new ArrayList<Integer>(m);
for (int i = 0; i < n; i++) { //swimmers
myname.add(input.next());
for (int j = 0; j < m; j++) { //judges
myscore.add(input.nextInt());
}
}
for (int x = 0; x < n; x++) { //name
System.out.println(myname.get(x));
for (int y = 0; y < m; y++) { //score
System.out.println(myscore.get(y));
}
}
Based on your code it seems that you have ‘n’ number of swimmers, each with ‘m’ number of scores. You are storing the names of the ‘n’ swimmers in an ArrayList, which is bad because you know the number will never change. A better approach to this would be to declare myname as a String[] of size n, and instead of calling myname.get(x) you would later call myname[x].
This however, is only symptomatically related to the problem at hand. You are storing all of your score results inside a single ArrayList. A better solution is to generate ‘n’ number of arrays (which is what I assume you would like to do based on the title of this question). This can be done by simply declaring
allScores[][] = new int[n][m]
This would let you access the values for swimmer number ‘n’ with allScores[n]. If this isn’t what you actually wanted to do then you can simply offset the values in your last get statement by the number of scores you’ve already processed (x*n).
TLDR: Change the line in your last for loop to read:
System.out.println(myscore.get(y + x*n)
Because you have a list myscore of n*m length not only m like you thought. You are adding at the end of the list every score.
So you have n blocks of m elements in the list. You could still print the value with
for(int y = x * m, to = x*m + m; y < to; ++y){
System.out.println(myscore.get(y));
}
class ScoreHolder{
String name = "";
ArrayList<Integer> scores = new ArrayList<Integer>;
public ScoreHolder(String name){
this.name = name
}
}
And then
ScoreHolder[] scores = new ScoreHolder[n];
for (int i = 0; i < n; i++) { //swimmers
scores[i] = new ScoreHolder(input.next());
for (int j = 0; j < m; j++) { //judges
scores[i].scores.add(input.nextInt());
}
}
for (int x = 0; x < n; x++) { //name
System.out.println(scores[x].name);
for (int y = 0; y < m; y++) { //score
System.out.println(scores[x].scores.get(y));
}
}
It won't be just easy to work with now but also a lot easier to make any changes or do anything else you want.
What I have done is simply created a holder class which will hold the swimmer's name and a list of all his scores.
This abstraction will now help you in getting the scores of the swimmers or doing anything else you now want with it.

Initializing a 2-D Array in java

Little confused why this isn't working could use a little help, I want to set all the values to false:
boolean[][] seatArray = new boolean[4][4];
for(int x = 0; x < seatArray.length; x++){
for(int y = 0; y < seatArray.length; y++){
seatArray[x][y] = false;
}
}
You have to ensure that you are iterating over the correct array element in your inside for loop to set every value to be false. Try this:
boolean[][] seatArray = new boolean[4][4];
for(int x = 0; x < seatArray.length; x++){
for(int y = 0; y < seatArray[x].length; y++){
seatArray[x][y] = false;
}
}
EDIT: Your code should still work, but for convention you should still probably do this.
You don't actually need to explicitly set any value.
The primitive boolean defaults to false.
Hence:
boolean[][] seatArray = new boolean[4][4];
System.out.println(seatArray[0][1]);
Output
false
BY defaultif u initialize a 2D boolean array it will contain value as false
Lets say you have a two dimensional array as
boolean[][] seatArray=new boolean[4][4];//all the value will be false by default
so it is a 4*4 matrix
boolean[0] represents the the 1st row i.e Lets say it contains value like {true,true,true,true} if you need the value in individual cell you need to iterate 2 for each loop like
for (boolean[] rowData: seatArray){
for(int cellData: rowData)
{
System.out.printn("the indiviual data is" +cellData);
cellData=Boolean.false;
}
}
Your code should work but here is another solution for filling a 2D array:
boolean[][] b = new boolean[4][4];
for (int i = 0; i < b.length; i++)
Arrays.fill(b[i], false);
Another way to make sense of iterating over multi dimensional arrays is like this.
boolean[][] seatArray = new boolean[4][4];
//Foreach row in seatArray
for(boolean[] arr : seatArray){
for(int i = 0; i < arr.length; i ++){
arr[i] = false;
}
}
If you have already given a constant size of array, avoid using .length and use the constant instead.
for(int x = 0; x < 4; x++){for(int y = 0; y < 4; y++){ ... ... }}

Java Union array of 2 int arrays using nested loops [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I want to create a union array for two integer arrays using nested loops.
This is my attempt so far:
import java.util.Scanner ;
public class array4 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter first array size:");
int size = input.nextInt();
int x[] = new int[size];
System.out.println("Enter first array elements:");
for (int i = 0; i < size; i++) {
x[i] = input.nextInt();
}
System.out.print("Enter second array size:");
int size2 = input.nextInt();
int y[] = new int[size2];
for (int i = 0; i < size2; i++) {
y[i] = input.nextInt();
}
System.out.println("Union");
for (int i = 0; i < size; i++) {
System.out.println(x[i]);
}
for (int i = 0; i < size2; i++) {
for (int z = 0; z < size; z++) {
if (y[i] != x[z]) {
System.out.println(y[i]);
}
}
}
}
}
Lets assume that we will print all numbers from second array, and only these numbers from first array which don't exist in second one. So
for each element in first array
test if it exist in second array (iterate over elements in second array and set some boolean flag like exists to true if x[i]==y[j])
if element doesn't exist in second array print it
iterate over elements from second array
and print them
Algorithm can look like
for (int i = 0; i <= x.length; i++) {// "<=" is not mistake,
// in last iteration we print all elements
// from second array
boolean exist = false;
for (int j = 0; j < y.length; j++) {
if (i < x.length) {
if (x[i] == y[j])
exist = true;
} else
System.out.println(y[j]);
}
if (!exist && i < x.length)
System.out.println(x[i]);
}
This algorithm can be probably rewritten to something simpler but I will leave it in this form for now.
For the lack of requirements, here is my answer for now... just basing on your current code.
for (int i = 0; i < size2; i++) {
for (int z = 0; z < size; z++) {
if (y[i] != x[z]) {
System.out.println(y[i]);
break; //added break
}
}
}
The problem was you're printing array elements without duplicate multiple times, to avoid that, you should add a break after you print the element with no duplicate.
By the way, your code is just printing the elements on both arrays, I thought you're suppose to combine them? Shouldn't you have a new array that contains both of the elements on the two arrays?
EDIT 2:
Add these lines of code after you get the two set of arrays without duplicate:
I also added comments to explain what's happening.
System.out.println("Union");
int[] unionArray = new int[size + size2]; //created a new array that will contain two arrays
for (int i = 0; i < size; i++) { //put the first set of int in the new array
unionArray[i] = x[i];
}
for (int i = size; i < unionArray.length; i++) { //put the second set
unionArray[i] = y[i-size]; //i = size : started with the last index of the first array
//y[i-size] : we are getting the elements on the second array
}
for (int i = 0; i < unionArray.length; i++) { //output
System.out.println(unionArray[i]);
}
Hope this helps. :)
If it's just to play with arrays and you don't need to use loops - try using a Java collection for that task, that's how most people would probably implement it:
init collection 1 from array 1
init collection 2 from array 2
add collection 2 to collection 1
convert collection 1 back to an array
That can be a (more or less) neat one-liner.

Categories

Resources