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

熱點內容
c資料庫壓縮 發布:2025-05-17 11:39:22 瀏覽:960
安卓手機如何連接音響功放 發布:2025-05-17 11:37:48 瀏覽:958
破解exe加密視頻 發布:2025-05-17 11:23:41 瀏覽:976
我的世界伺服器圈太大了怎麼辦 發布:2025-05-17 11:15:21 瀏覽:614
便宜的免費雲伺服器 發布:2025-05-17 11:08:50 瀏覽:777
中國頂級dhcp解析伺服器地址 發布:2025-05-17 11:06:27 瀏覽:34
php轉義html 發布:2025-05-17 11:04:00 瀏覽:567
鋼筋籠加密區規范 發布:2025-05-17 10:59:50 瀏覽:4
我的世界網易手機版主播伺服器房號 發布:2025-05-17 10:40:59 瀏覽:227
豎編譯 發布:2025-05-17 09:56:08 瀏覽:229