Menghapus elemen array
import javax.swing.JOptionPane;public class HapusArray {ring[] args) { int[] data = new int[5];public static void main(S t for(int index=0; index < data.length; index++) {data[index] = (int) (Math.random()*100)+20;}System.out.println("Data awal");System.out.println("---------");for(int index=0; index < data.le ngth; index++) {ln("data" + "[" + index + "]" + data[index]); } int cari =System.out.prin tInteger.parseInt(JOptionPane.showInputDialog(null, "Data yang dihapus:"));if(data[index] == cari)boolean ketemu = false; for(int index=0; index < data.length; index++) { { ketemu = true;= 0; fbreak; } } if (ketemu == true) { int[] temporary = new int[data.length-1]; int counter or(int i=0; i<temporary.length; i++) { if(data[i] == cari) { counter++;[counter]; counter++; } }temporary[i] = data[counter]; counter++; } else { temporary[i] = dat a data = new int[temporary.length]; System.out.println("");println("------------------------"); for(int iSystem.out.println("setelah penghapusan data"); System.out .=0; i<data.length; i++) { data[i] = temporary[i]; System.out.println("data" + "[" + i + "]" + data[i]); }} else { JOptionPane.showMessageDialog(null, "tidak ada"); } }}
output program:
Data awal---------data[1]66data[0]10 5 data[2]98ta[4]107data[3]65 d a setelah penghapusan data ------------------------ data[0]105 data[1]66 data[2]65 data[3]107
Menyisipkan elemen array
import javax.swing.JOptionPane;public class SisipArray {ring[] args) { int[] data = new int[5];public static void main(S t //int[] temporary = new int[data.length+1];{ data[index] = (int) (Math.random()*100)+20; }for(int index=0; index < data.length; index++) System.out.println("Data awal"); System.out.println("---------");ata" + "[" + index + "]" + " = " + data[index]);for(int index=0; index < data.length; index++) { System.out.println(" d } int sisip = Integer.parseInt(JOptionPane.showInputDialog(null, "Data yang ditambahkan:"));<0 || lokasi>data.length-1) { JOptionPane.showMessageDialog(null, "anda salah meng-int lokasi = Integer.parseInt(JOptionPane.showInputDialog(null, "Pada index ke:")); if (lokas iinputkan index"); } else { int[] temporary = new int[data.length+1]; for(int index=0; index < lokasi; index++){ temporary[index] = data[index]; } temporary[lokasi] = sisip;a[index] = temporary[index]; } } System.out.printfor(int index=lokasi; index < data.length; index++){ temporary[index+1] = data[index]; } data = new int[temporary.length]; for (int index=0; index<data.length; index++) { da tln(" "); System.out.println("Setelah penyisipan"); System.out.println("------------------"); for(int index=0; index<data.length; index++) { System.out.println("data" + "[" + index + "]" + " = " + data[index]); } }}
output program:
Data awal---------32 data[1] =data[0] = 111 data[2] = 874] = 22data[3] = 106 data[Setelah penyisipan------------------] = 111 datadata[0] = 32 data[ 1[2] = 87 data[3] = 7622data[4] = 106 data[5]=
0 Komentar:
Posting Komentar