更改两个数组之间的值

时间:2015-10-21 18:48:37

标签: java arrays

我有一个4 int的数组,我需要用另一个数组的值替换它们。例如:我有一个数组{5,3,7,2},我需要替换值并获取数组{2,7,3,5}

这是我的代码:

public static void main(String args[]){
    int array[] = new int[4];
    array[0] = 1;
    array[1] = 4;
    array[2] = 3;
    array[3] = 7;
    int swapArray[] = new int[5];

    for (int j = 3; j > 0; j--) {
        for (int i = 0; i < 4; i++) {
            swapArray[j] = array[i];
            System.out.print(" " + swapArray[j]);
        }
    }
}

但它不会改变数值,只重复3次。

3 个答案:

答案 0 :(得分:3)

也许是这样的:

  public static void main(String args[]){
    int array[] = {1,4,3,7};
    int swapArray[] = new int[array.length];
    for(int i=0;i<array.length;i++)
         swapArray[i]=array[array.length-1];
         System.out.print(" " + swapArray[i]);
        }
    }

答案 1 :(得分:2)

您似乎想要反转数组。你可以这样做,

function formuserentry_menu() {

  $items = array();

  $items['formuserentry'] = array( //this creates a URL that will call this form at "examples/form-example"
    'title' => 'Entry Page',

    'page callback' => array('formuserentry_view'),

    'access callback' => TRUE,

    'type' => MENU_NORMAL_ITEM

  );

  $items['formuserentry/application'] = array( //this creates a URL that will call this form at "examples/form-example"
    'title' => 'Entry Application Forms', //page title
    'description' => 'A form to mess around with.',
    'page callback' => 'drupal_get_form', //this is the function that will be called when the page is accessed.  for a form, use drupal_get_form
    'page arguments' => array('formuserentry_application' , 2), //put the name of the form here
    'access arguments' => array('administer your module'),
  );


  return $items;
}


/********** front page view ***********/


function formuserentry_view() {
 $result = 'My  Sub Menu URL was hit';

 $header = array('Entry Id','Name', 'DOB', 'Year', 'Image' );
  $rows = array();
  $no_yes = array('No', 'Yes');

  $results = db_query("SELECT * FROM userentryform ORDER BY userentryId DESC");

      foreach ($results as $node) {
        $rows[] = array(
                    l($node->firstname, 'formuserentry/application/'. $node->userentryId ),


            array('data' => $node->firstname, 'class' => 'title'),
            array('data' => $node->lastname, 'class' => 'type'),
            array('data' => $node->birthyear, 'class' => 'type'),
            array('data' => '<img src="sample.jpg">dff', 'class' => 'image'),
            );
       }
  return theme('table', array('header' => $header, 'rows' => $rows));



}

/********************** add form ***************************/


function formuserentry_application($form, &$form_state, $candidateId) {

    $firstname = ''; 
    $lastname = ''; 
    $birthyear = ''; 

    /****** query fetch ******/
    if(isset($candidateId)){
     $fetchquery = db_select('userentryform', 'n')
              ->fields('n', array('firstname','lastname', 'birthyear'))
              ->fields('n')
              ->condition('userentryId',$candidateId)
              ->execute()
              ->fetchAll();

            $firstname = $fetchquery[0]->firstname; 
            $lastname = $fetchquery[0]->lastname; 
            $birthyear = $fetchquery[0]->birthyear; 
    }

    /**************************/
    //print($fetchquery);
   //drupal_set_message('<pre>'. print_r($fetchquery[0]->firstname, TRUE) .'</pre>');
  $form['name'] = array(
    '#type' => 'fieldset',
    '#title' => t('Name'),
    '#collapsible' => TRUE,
    '#collapsed' => FALSE,
  );
  $form['name']['first'] = array(
    '#type' => 'textfield',
    '#title' => t('First Name'),
    '#required' => TRUE,
    '#default_value' => $firstname,
    '#description' => "Please enter your first name.",
    '#size' => 20,
    '#maxlength' => 20,
  );

  $form['name']['canid'] = array(
    '#type' => 'hidden',
    '#required' => FALSE,
    '#default_value' => $candidateId,
    '#description' => "Please enter your first name.",
    '#size' => 20,
    '#maxlength' => 20,
  );

  $form['name']['last'] = array(
    '#type' => 'textfield',
    '#title' => t('Last name'),
    '#value' => $lastname,
    '#required' => TRUE,
  );
  $form['name']['year_of_birth'] = array(
    '#type' => 'textfield',
    '#title' => "Year of birth",
    '#description' => 'Format is "YYYY"',
    '#value' => $birthyear,
    '#required' => TRUE,
  ); 

    // Image upload field.
   $form['name']['image'] = array(
    '#type' => 'managed_file',
    '#title' => 'File',
    '#upload_location' => 'public://my-files/',
    '#process' => array('formuserentry_my_file_element_process'),
    "#upload_validators"  => array('file_validate_is_image' => array())
  );



  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => 'Submit',
  );
  return $form;

}

/*********  for validation ************/

> function formuserentry_my_file_element_process($element, &$form_state,
> $form) {   $element = file_managed_file_process($element, $form_state,
> $form);   $element['upload_button']['#access'] = FALSE;   return
> $element; }
> 
> function formuserentry_application_validate($form, &$form_state) {  
> $year_of_birth = $form_state['values']['year_of_birth'];
>     if ($year_of_birth && ($year_of_birth < 1900 || $year_of_birth > 2000)) {
>         form_set_error('year_of_birth', 'Enter a year between 1900 and 2000.');
>     } }

/********** form submission ***************/

    function formuserentry_application_submit($form, &$form_state) {
        $first_name    = $form_state['values']['first']; 
        $last_name     = $form_state['values']['last'];
        $year_of_birth = $form_state['values']['year_of_birth'];
        $profileimage      = $form_state['values']['image'];

        $canid      = $form_state['values']['canid'];

        if($canid == '') {
            $nid = db_insert('userentryform')
                  ->fields(array(
                    'firstname' => $form_state['values']['first'],
                    'lastname' => $form_state['values']['last'],
                    'birthyear' => $form_state['values']['year_of_birth'],
                    'profileimage' =>  $form_state['values']['profileimage'],
                  ))
                  ->execute(); 
            drupal_set_message(t('The form has been Added your last insert ID is => '.$nid));     
        } else {


        $nid = db_update('userentryform')
                  ->fields(array(
                    'firstname' => $form_state['values']['first'],
                    'lastname' => $form_state['values']['last'],
                    'birthyear' => $form_state['values']['year_of_birth']
                  ))
                  ->condition('userentryId',$canid)
                  ->execute(); 
        drupal_set_message(t('The form has been Updated your last insert ID is => '.$nid));

        }
        drupal_goto("/formuserentry/");





    }

或者,您可以将其复制到新的(反向)数组,如

int[] arr = { 5, 3, 7, 2 };
System.out.println(Arrays.toString(arr));
for (int i = 0; i < arr.length / 2; i++) {
  int t = arr[i];
  arr[i] = arr[arr.length - i - 1];
  arr[arr.length - i - 1] = t;
}
System.out.println(Arrays.toString(arr));

两个示例输出(请求的)

int[] arr = { 5, 3, 7, 2 };
System.out.println(Arrays.toString(arr));
int[] arr2 = new int[arr.length];
for (int i = 0; i < arr.length; i++) {
  arr2[arr2.length - i - 1] = arr[i];
}
System.out.println(Arrays.toString(arr2));

答案 2 :(得分:0)

如果你想反转一个数组:

使用Commons.Lang,你可以简单地使用

int array[] = new int[4];
array[0] = 1;
array[1] = 4;
array[2] = 3;
array[3] = 7;

ArrayUtils.reverse(array);
// For print output
System.out.println(Arrays.toString(array));
// Print output [7, 3, 4, 1]