[英]How do I rewrite my code so that the value of 0 does not give me a out of bounds error in java?
[英]How do i optimize below code so that it can accept any array size and give me the result
下面的代碼顯示給定數組的子數組。 但是,如果我將數組大小增加1,則以下代碼無法顯示所有子數組,要使其成功顯示所有數組,我需要再添加一個for循環。 因此,我如何優化代碼,使其不依賴於數組大小而動態顯示所有子數組。
public class Subarrays {
public static void main(String[] args)
{
int[] arr=new int[] {1,-2,4,-5,1};
int count=0;
for(int i=0; i<arr.length; i++) {
System.out.println("["+arr[i]+"]");
for(int j=0; j<arr.length-(i+1); j++) {
}
}
for(int i=0; i<arr.length-1; i++) {
System.out.println("["+arr[i]+","+arr[i+1]+"]");
}
for(int i=0; i<arr.length-2;i++)
{
System.out.println("["+arr[i]+","+arr[i+1]+","+arr[i+2]+"]");
}
for(int i=0; i<arr.length-3; i++) {
System.out.println("["+arr[i]+","+arr[i+1]+","+arr[i+2]+","+arr[i+3]+"]");
}
for(int i=0; i<arr.length-4; i++) {
System.out.println("["+arr[i]+","+arr[i+1]+","+arr[i+2]+","+arr[i+3]+","+arr[i+4]+"]");
}
}
}
public static void printAllSubArrays(int[] arr) {
for (int len = 1; len <= arr.length; len++) {
for (int from = 0; from + len <= arr.length; from++) {
System.out.print('[');
for (int i = from; i < from + len; i++) {
if (i != from)
System.out.print(',');
System.out.print(arr[i]);
}
System.out.println(']');
}
}
}
演示:
printAllSubArrays(new int[] { 1, -2, 4, -5, 1 });
輸出:
[1]
[-2]
[4]
[-5]
[1]
[1, -2]
[-2, 4]
[4, -5]
[-5, 1]
[1, -2, 4]
[-2, 4, -5]
[4, -5, 1]
[1, -2, 4, -5]
[-2, 4, -5, 1]
[1, -2, 4, -5, 1]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.