JAVA基礎(數組)數組排序和尋找數組中是否還有某一個數

來源:互聯網
上載者:User

標籤:變數   [1]   引用   []   binary   rgs   --   str   system   

數組排序和數組中含有某一個數

import java.util.Arrays;
class Demo4
{
public static void main(String[] args)
{

//數組中的使用工具:Arrays

int[] arr = {1,2,4,5};

//尋找數組中是否還有某一個數
int num = 3;

//有 : 對應索引位置
int result = Arrays.binarySearch(arr,num);

System.out.println(result); // -3

//做排序:

int[] arr1 = {6,2,7,5,8};
Arrays.sort(arr1);

for (int i = 0;i < arr1.length ;i++ )
{
System.out.println(arr1[i]);
}
}
}


輸入一個數擷取它的每個各個位
class Demo2
{
public static void main(String[] args)
{

/*輸入一個整數 : 678 ---> 8,7,6*/
// ---- 目的就是鍛煉大家如何擷取一個數的各個位。
int num = 678;

//取出這個數中的每一位
//個位
int g = num % 10;
int s = (num / 10) % 10;
int p = (num / 100);


}
}

建立一個Int類型
class Demo3
{
public static void main(String[] args)
{

//建立一個int類型的數組
//arr : 是一個變數 只是數組的一個引用地址
//局部變數存在棧中
//成員變數 -- 屬性 --- > 對堆區中
//靜態變數 --- > 共用地區
int[] arr = new int[2];
arr[1] = 10;

arr = null;


int[] arr1 = new int[2];
arr1[1] = 20;

System.out.println(arr[1]);// 10

int[] arr2 = arr;
arr2[1] = 30;

System.out.println(arr[1]);// 10

}
}

插入歌曲 按首字母排序到指定位置
class Demo1
{
public static void main(String[] args)
{

/*
5. 有如下歌曲數組

String[] musics = new String[]{"Island","Ocean","Pretty","Sun"};
//這是按照字母順序排好序的 字串數組

現在要往裡面插入新的英文歌曲,
按照首字母排序插入到指定的位置

提示: musics[i].compareToIgnoreCase(music) > 0
上面這個方法是比較字串的方法,
如果前面的值大返回1,如果後面的大於前面的,返回-1,或者等於前面的,返回0

*/
String[] musics = new String[]{"Island","Ocean","Pretty","Sun"};

//1.用冒泡排序,給歌曲排序
for(int i = 0;i<musics.length-1;i++){

for(int j = 0; j<musics.length-1-i;j++){

if( musics[j].compareToIgnoreCase(musics[j+1])>0){

//如果前面的大於後面的就交換位置
String temp = musics[j];
musics[j] = musics[j+1];
musics[j+1] = temp;


}
}
}

//插入一個歌曲
String[] newMusics = new String[musics.length+1];

//定義一個插入的歌曲
String songName = "Love";


//用迴圈讓songName 和 原歌曲列表做對比

//預設就在第一個
for(int i = 0;i<musics.length +1;i++){

if(i == 0){

newMusics[i] = songName;
}


newMusics[i] = musics[i-1];

}

//將數組在一個插入排序。 /*查資料*/


//遍曆數組
for(int i = 0;i<musics.length;i++){

System.out.println(musics[i]);

}
}
}

 

JAVA基礎(數組)數組排序和尋找數組中是否還有某一個數

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.