Java Returning a Correctly Sized Array for Dive Moves

  • Thread starter Thread starter testme
  • Start date Start date
  • Tags Tags
    Array Java
AI Thread Summary
The discussion revolves around returning a correctly sized array in a Java program that simulates a diving scenario. The user seeks to return only the filled portion of an array that tracks moves made by a diver, as the current implementation includes uninitialized elements. Suggestions include using a while loop to determine the actual size of the filled array and creating a new array to return only the relevant moves. The conversation emphasizes the importance of managing array sizes effectively, particularly when dealing with uninitialized values. Ultimately, the focus is on ensuring that the program accurately reflects the diver's actions without extraneous data.
testme
Messages
68
Reaction score
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


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}
 


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.
 


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:


Is the size of this object determined at run-time or known before hand?
 
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:
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?)
 

Similar threads

Replies
13
Views
4K
Replies
31
Views
3K
Replies
23
Views
2K
Replies
8
Views
4K
Replies
29
Views
3K
Replies
65
Views
6K
Back
Top