Java 中用 -6 替換末位數字為 6 的陣列元素


在 Java 中,陣列是一個物件。它是一種非基本資料型別,用於儲存相同資料型別的值。

根據問題陳述,我們有一個包含一些隨機值的陣列,我們需要找到是否有任何元素的末位數字為 6 或元素本身等於 6,然後我們將該元素替換為 -6。

讓我們探索本文,瞭解如何使用 Java 程式語言來實現它。

為您展示一些示例

示例 1

Given Array= [21, 16, 18, 5, 6].
Replace the digit 6 from the given array with -6.
New array = [21, -6, 18, 5, -6]

示例 2

Given Array= [38, 94, 86, 63, 36].
Replace the digit 6 from the given array with -6.
New array = [38, 94, -6, 63, -6]

示例 3

Given Array= [54, 67, 26, 95, 24, 60].
Replace the digit 6 from the given array with -6.
New array = [54, 67, -6, 95, 24, 60]

演算法

  • 步驟 1 - 宣告並初始化一個數組。

  • 步驟 2 - 宣告另一個與給定陣列長度相同的空陣列。

  • 步驟 3 - 使用 for 迴圈檢查給定陣列的每個元素,並檢查其末位數字是否為 6。

  • 步驟 4 - 如果存在任何以數字 6 結尾的元素,則將其替換為 -6。

  • 步驟 5 - 獲取結果陣列後,將其列印輸出。

語法

要獲取陣列的長度(陣列中元素的數量),陣列有一個內建屬性,即length。

以下是其語法:

array.length

其中,“array”指的是陣列引用。

多種方法

我們提供了不同的方法來解決這個問題。

  • 使用靜態陣列初始化。

  • 使用使用者定義的方法。

讓我們逐一檢視程式及其輸出。

方法 1:使用靜態陣列初始化

在這種方法中,我們宣告並初始化一個數組,並使用演算法,如果任何元素的末位數字為 6,則將其替換為 -6。

示例

import java.util.*;
public class Main {
   public static void main(String args[]) {
     
      // declare an integer type of array and store some random value to it by static input method
      int[] inputArray = { 264, 926, 6, 52 , 21,54};
     
      //declare an empty array to store the modified array
      int[] newArray = new int[inputArray.length];
     
      //initiate the loop to replace the digit-6 with "-6"
      for(int i=0,j=0;i<inputArray.length;i++) {
         if(inputArray[i]%10==6) {
            newArray[i]=-6;
         } else {
            newArray[i]=inputArray[i];
         }
      }
      //print the resultant array
      System.out.println("Resultant array: " + Arrays.toString(newArray));
   }
}

輸出

Resultant array: [264, -6, -6, 52, 21, 54]

方法 2:使用使用者定義的方法

在這種方法中,我們宣告並初始化一個數組。然後透過將此陣列和給定數字作為引數傳遞給使用者定義的方法來呼叫它,然後在方法內部使用演算法,如果任何元素的末位數字為 6,則將其替換為 -6。

示例

import java.util.*;
public class Main {
   public static void main(String args[]) {
     
      // declare an integer type of array and store some random value to it by static input method
      int[] inputArray = { 26, 92, 61, 56 , 6};
      changeDigit(inputArray);
   }
   public static void changeDigit(int[] arr) {
      int[] newArray = new int[arr.length];
      for(int i=0,j=0;i<arr.length;i++){
         if(arr[i]%10==6){
            newArray[i]=-6;
         } else {
            newArray[i]=arr[i];
         }
      }
      System.out.println("Resultant array: " + Arrays.toString(newArray));
   }
}

輸出

Resultant array: [-6, 92, 61, -6, -6]

在本文中,我們探討了如何使用 Java 程式語言,如果任何元素的末位數字為 6,則將其替換為 -6。

更新於: 2023 年 2 月 2 日

187 次瀏覽

開啟你的職業生涯

透過完成課程獲得認證

開始學習
廣告

© . All rights reserved.