當前位置:首頁 » 編程語言 » 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("[\[\],]",""));
}
}

熱點內容
安卓編譯打包 發布:2025-07-15 04:24:20 瀏覽:167
bat編譯器 發布:2025-07-15 04:18:07 瀏覽:54
中興伺服器登錄地址 發布:2025-07-15 04:02:47 瀏覽:988
手提箱怎麼改密碼 發布:2025-07-15 03:55:47 瀏覽:219
did腳本 發布:2025-07-15 03:55:12 瀏覽:963
殘留溶劑線性濃度如何配置 發布:2025-07-15 03:54:31 瀏覽:134
部落沖突好號密碼是什麼 發布:2025-07-15 03:48:45 瀏覽:971
存儲氣瓶 發布:2025-07-15 03:48:10 瀏覽:992
數據解鎖密碼有什麼用 發布:2025-07-15 03:35:27 瀏覽:196
騰訊公認的密碼是多少 發布:2025-07-15 03:34:44 瀏覽:626