[Java] Returning an Array

  • Java
  • Thread starter testme
  • Start date
  • Tags
    Array Java
In summary: Diving ChancePlease enter the maximum time in seconds to make a dive: 5The man jumped with the moves F, G, B, F, G in 5 seconds.
  • #1
testme
68
0
If I have a program where I need to return an array, is it possible that I only return the array with the length of what was added to it?

What I mean is I have an array that gets filled up with letters but it doesn't always get completely filled up.

Is there a way I can only return the filled up part (including having only it's size)

Ex: array[4] = {?, ?, ?, ?, ?}

fills up to array[4] = {F, B, F, G,?}

and when I return it I only want an array like this

arr[3] = {F, B, F, G}
 
Technology news on Phys.org
  • #2


testme said:
If I have a program where I need to return an array, is it possible that I only return the array with the length of what was added to it?
It's hard to answer your question without knowing what language you are writing code in.
testme said:
What I mean is I have an array that gets filled up with letters but it doesn't always get completely filled up.

Is there a way I can only return the filled up part (including having only it's size)

Ex: array[4] = {?, ?, ?, ?, ?}
Why do you have 5 question marks in an array that has 4 elements?
testme said:
fills up to array[4] = {F, B, F, G,?}

and when I return it I only want an array like this

arr[3] = {F, B, F, G}
 
  • #3


Oops, sorry, it's late at night here. I'm using Java and bump those up 1. I was thinking as though I'm reading an element from the array.
 
  • #4


testme said:
If I have a program where I need to return an array, is it possible that I only return the array with the length of what was added to it?

What I mean is I have an array that gets filled up with letters but it doesn't always get completely filled up.

Is there a way I can only return the filled up part (including having only it's size)

Ex: array[4] = {?, ?, ?, ?, ?}

fills up to array[4] = {F, B, F, G,?}

and when I return it I only want an array like this

arr[3] = {F, B, F, G}

Possible, yes (see below, for example). Sensible, probably not. Why work with arrays of Letters instead of a String? What exactly are you trying to do?

Code:
import java.util.Arrays;

public class ArrayTest {

	public static void main(String[] args) {
		char[] testArray = {'F', 'B', 'F', 'G','?'};
		char[] filledArray = getFilledArray(testArray);
		for(char c : filledArray) {
			System.out.println(c);
		}
	}
	
	private static char[] getFilledArray(char[] inputArray) {
		String str = Arrays.toString(inputArray);
		str = str.replaceAll("[\\[\\]? ,]", "");
		char[] outputArray = str.toCharArray();
		return outputArray;
	}
	
}
 
Last edited:
  • #5


Is the size of this object determined at run-time or known before hand?
 
  • #6
Here is my program so you can see what I need. This program is supposed to check if a person dives on a diving board or doesn't because of their nerves. Every step they take is 2 feet and they have to move 10 feet to dive. If they have nerves and step back they move back 2 feet.

Code:
/**
 * This program will determine whether a person will dive or not using
 * the probability of someone to jump due to nerves
 */

class Dive 
{
  public static void main (String args[ ])
  {
    // DECLARE VARIABLES/DATA DICTIONARY
    int tMax; //the maximum number of seconds the diver has to dive
    char[] moves; //reference to a character array showing the sequence of man’s moves
    int num; //the number of seconds taken by the diver to dive
    char again; //the character that will determine whether  the user wants to run another trial

    System.out.println("Diving Chance");
    do
    {
    System.out.println("Please enter the maximum time in seconds to make a dive: ");  
    
    // READ IN GIVENS use our ITI1120 special class for keyboard input 
    tMax = ITI1120.readInt(); //reads in the user's choice
    
    // BODY OF ALGORITHM - Call to the method to solve problem
    moves = dive(tMax); //call to the method
    num = moves.length; //gets the length of the array and removes 1 
    
    // PRINT OUT RESULTS AND MODIFIEDS
    if(moves[num - 1] == 'D') //checks to see if the man dived or not
    {
      System.out.print("The man jumped with the moves ");
      for(int i = 0; i < num; i++) //loop that goes through the array of moves and prints each letter out
      {
      System.out.print(moves[i]);
      }
      System.out.println(" in "+num+" seconds");
    }
    /*else
    {
      System.out.print("The man lost his nerves after the moves ");
      for(int i = 0; i < num; i++) //loop that goes through the array of moves and prints each letter out
      {
      System.out.print(moves[i]);
      }
      System.out.println();
    }*/
    System.out.println("Do you wish to make another dive attempt? (y/n): ");
    again = ITI1120.readChar(); //reads in user's input for starting another run
    if(again == 'n')
    {
      System.out.println("Program terminated!");
    }
    }while(again == 'y');
  }
  
  // Problem Solving Method
  // Description: Determines if the man dives or not
  // Parameters (GIVENS): 
  //    tMax - the maximum number of seconds the diver has to dive
  public static char[] dive(int tMax)
  {  
    // DECLARE VARIABLES/DATA DICTIONARY
    
    // INTERMEDIATES
    int x = 0; //the man's distance in feet
    int index = 0; //the index number for the element in the array
    double p; //the probability of taking a step forward
    double ranNum; //a random number
    
    // RESULT
    char diveRes[] = new char[tMax]; //an array that holds the moves takens, F - foward, B - backward, D - dive
    
    // BODY OF ALGORITHM
    while(index < tMax && x < 10) //keeps going as long we haven't exceeded the maximum time allowed or the man hasn't dived
    {
      ranNum = Math.random(); //creates the random number from 0.0 to 1.0
      p = 1.0 - (x/10.0); //calculates the probability 
      if(ranNum < p)
      {
        x = x + 2;
        diveRes[index] = 'F';
      }
      else
      {
        if(x != 0)
        {
        x = x - 2;
        }
        diveRes[index] = 'B';
      }
      index++;
    }
    if(x == 10) //sets the last element in the array to D if the man dives
    {
      diveRes[index - 1] = 'D';
    }
    // RETURN RESULT
   return diveRes;
  }
  
} // Don't remove this brace bracket!

Where my problem lies is in the main method where I'm checking if moves[num-1] == 'D' because num is getting the length of the full array which has a bunch of garbage at the end so it doesn't know that the last letter really was a D.

We were also told we're not allowed to use strings.
 
Last edited:
  • #7
testme said:
Here is my program so you can see what I need. This program is supposed to check if a person dives on a diving board or doesn't because of their nerves. Every step they take is 2 feet and they have to move 10 feet to dive. If they have nerves and step back they move back 2 feet.

Code:
/**
 * This program will determine whether a person will dive or not using
 * the probability of someone to jump due to nerves
 */

class Dive 
{
  public static void main (String args[ ])
  {
    // DECLARE VARIABLES/DATA DICTIONARY
    int tMax; //the maximum number of seconds the diver has to dive
    char[] moves; //reference to a character array showing the sequence of man’s moves
    int num; //the number of seconds taken by the diver to dive
    char again; //the character that will determine whether  the user wants to run another trial

    System.out.println("Diving Chance");
    do
    {
    System.out.println("Please enter the maximum time in seconds to make a dive: ");  
    
    // READ IN GIVENS use our ITI1120 special class for keyboard input 
    tMax = ITI1120.readInt(); //reads in the user's choice
    
    // BODY OF ALGORITHM - Call to the method to solve problem
    moves = dive(tMax); //call to the method
    num = moves.length; //gets the length of the array and removes 1 
    
    // PRINT OUT RESULTS AND MODIFIEDS
    if(moves[num - 1] == 'D') //checks to see if the man dived or not
    {
      System.out.print("The man jumped with the moves ");
      for(int i = 0; i < num; i++) //loop that goes through the array of moves and prints each letter out
      {
      System.out.print(moves[i]);
      }
      System.out.println(" in "+num+" seconds");
    }
    /*else
    {
      System.out.print("The man lost his nerves after the moves ");
      for(int i = 0; i < num; i++) //loop that goes through the array of moves and prints each letter out
      {
      System.out.print(moves[i]);
      }
      System.out.println();
    }*/
    System.out.println("Do you wish to make another dive attempt? (y/n): ");
    again = ITI1120.readChar(); //reads in user's input for starting another run
    if(again == 'n')
    {
      System.out.println("Program terminated!");
    }
    }while(again == 'y');
  }
  
  // Problem Solving Method
  // Description: Determines if the man dives or not
  // Parameters (GIVENS): 
  //    tMax - the maximum number of seconds the diver has to dive
  public static char[] dive(int tMax)
  {  
    // DECLARE VARIABLES/DATA DICTIONARY
    
    // INTERMEDIATES
    int x = 0; //the man's distance in feet
    int index = 0; //the index number for the element in the array
    double p; //the probability of taking a step forward
    double ranNum; //a random number
    
    // RESULT
    char diveRes[] = new char[tMax]; //an array that holds the moves takens, F - foward, B - backward, D - dive
    
    // BODY OF ALGORITHM
    while(index < tMax && x < 10) //keeps going as long we haven't exceeded the maximum time allowed or the man hasn't dived
    {
      ranNum = Math.random(); //creates the random number from 0.0 to 1.0
      p = 1.0 - (x/10.0); //calculates the probability 
      if(ranNum < p)
      {
        x = x + 2;
        diveRes[index] = 'F';
      }
      else
      {
        if(x != 0)
        {
        x = x - 2;
        }
        diveRes[index] = 'B';
      }
      index++;
    }
    if(x == 10) //sets the last element in the array to D if the man dives
    {
      diveRes[index - 1] = 'D';
    }
    // RETURN RESULT
   return diveRes;
  }
  
} // Don't remove this brace bracket!

Where my problem lies is in the main method where I'm checking if moves[num-1] == 'D' because num is getting the length of the full array which has a bunch of garbage at the end so it doesn't know that the last letter really was a D.

We were also told we're not allowed to use strings.

This sounds like a homework problem. Progamming homework questions should be posted in the Engineering, Comp Sci, and Technology homework subforum.

What was the original programming assignment? Have you tried using a simple while loop to find the last letter in your moves array? Have you tried returning a correctly sized array from your dive method? (Right before your return statement, what will the value of index be? Do you see how you can use this to define a new array of the correct size and copy over the letters from diveRes to it, and then return it instead of
diveRes?)
 

1. What is the purpose of returning an array in Java?

The purpose of returning an array in Java is to allow a method to return multiple values of the same data type. This can be useful for situations where a method needs to return more than one piece of data, such as in sorting algorithms or when working with large amounts of data.

2. How do you return an array in Java?

To return an array in Java, you can declare a method with the data type of the array and use the return statement followed by the array name. For example, public int[] returnArray() { return myArray; } This will return an array of integers named myArray.

3. Can you return an array of a different data type in Java?

Yes, you can return an array of a different data type in Java. The data type of the array in the method declaration must match the data type of the array being returned. For example, if the method is declared as public String[] returnArray(), the array being returned must also be of type String[].

4. How do you access the elements of a returned array in Java?

To access the elements of a returned array in Java, you can assign the returned array to a variable and then use array indexing to access specific elements. For example, int[] myArray = returnArray(); int firstElement = myArray[0]; This will assign the first element of the returned array to the variable firstElement.

5. Is it possible to return a null array in Java?

Yes, it is possible to return a null array in Java. This can be useful in situations where there is no data to return or when an error occurs. To return a null array, use the keyword null in the return statement. For example, public int[] returnNullArray() { return null; } This will return a null array of integers.

Similar threads

  • Programming and Computer Science
Replies
13
Views
996
  • Programming and Computer Science
Replies
31
Views
2K
  • Programming and Computer Science
Replies
13
Views
3K
  • Programming and Computer Science
Replies
5
Views
1K
  • Programming and Computer Science
Replies
15
Views
3K
  • Programming and Computer Science
Replies
17
Views
2K
  • Programming and Computer Science
Replies
23
Views
1K
Replies
3
Views
706
  • Programming and Computer Science
Replies
29
Views
1K
  • Programming and Computer Science
Replies
8
Views
1K
Back
Top