當前位置:首頁 » 編程語言 » java數組添加數組

java數組添加數組

發布時間: 2023-06-05 23:09:02

java數組添加元素

case 4的代碼有些邏輯問題,其實已經添加成功了,只不過你對 fruit 進行循環,導致循環了5次,每次循環都要添加一次。

正確的做法是,先找出空位置,記錄下這個空位置的索引,然後再添加,更改後的 case 4 如下代碼:

case4://添加水果

intpos=-1;

//先找到一個空位
for(inti=0;i<fruit.length;i++){
if(fruit[i]==null){
pos=i;
}
}

//如果pos!=-1說明有空位,否則沒有位置添加新水果
if(pos!=-1){

System.out.println("請輸入要添加的水果:");
Stringname=input.next();
fruit[pos]=name;

}else{
System.out.println("沒有位置添加水果!");
}

break;

Ⅱ Java 用for循環向一個一維數組中添加數據

源代碼:

import java.util.Scanner;

public class addElement {

public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println("輸入需要的數組大小:");
Scanner scan=new Scanner(System.in);
int n = scan.nextInt();//接受輸入的數組大小
int[]arr=new int[n];//定義一個大小為剛輸入的n的數組
System.out.println("輸入數組的每個元素:");
for(int i=0;i<arr.length;i++)
arr[i]=scan.nextInt();//依次輸入元素到arr[i]
System.out.println("數組的元素依次為:");
for(int i=0;i<arr.length;i++)
System.out.print(arr[i]+" ");
}

}

Ⅲ java數組插入數組

importjava.util.*;
classTester{
publicstaticvoidmain(String[]args){
char[]cs={'a','b','c','e','f','p','u','z'};
System.out.format("插入前的序列是:%s%n",Arrays.toString(cs).replaceAll("[\[\],]",""));
Scannersc=newScanner(System.in);
System.out.print("待插入的字元是:");
Stringm=sc.next();
System.out.println(m);
System.out.print("插入字元的下標是:");
intindex=sc.nextInt();
System.out.println(index);
sc.close();
char[]dest=newchar[cs.length+1];
System.array(cs,0,dest,0,index);
dest[index]=m.charAt(0);
System.array(cs,index,dest,index+1,dest.length-index-1);
cs=dest;
System.out.format("插入後的字元序列是:%s",Arrays.toString(cs).replaceAll("[\[\],]",""));
}
}

熱點內容
java返回this 發布:2025-10-20 08:28:16 瀏覽:710
製作腳本網站 發布:2025-10-20 08:17:34 瀏覽:972
python中的init方法 發布:2025-10-20 08:17:33 瀏覽:681
圖案密碼什麼意思 發布:2025-10-20 08:16:56 瀏覽:833
怎麼清理微信視頻緩存 發布:2025-10-20 08:12:37 瀏覽:741
c語言編譯器怎麼看執行過程 發布:2025-10-20 08:00:32 瀏覽:1081
郵箱如何填寫發信伺服器 發布:2025-10-20 07:45:27 瀏覽:312
shell腳本入門案例 發布:2025-10-20 07:44:45 瀏覽:192
怎麼上傳照片瀏覽上傳 發布:2025-10-20 07:44:03 瀏覽:880
python股票數據獲取 發布:2025-10-20 07:39:44 瀏覽:837