我在写程序时,发现我的方法中的for循环多执行了一次,我有些不太明白为什么会这样,希望可以指点一下
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
public class A2_Box {
//delete the first element
public static int[] removeFirstElement(int[] arr) {
return Arrays.copyOfRange(arr, 1, arr.length);
}
//how to get final result
//let we start from index 0
public static int getResult(int m,int[] arr){
ArrayList<Integer> arrayList =new ArrayList<Integer>();
int len=0;//the number of positive result
int sum=0;//the sum of arr
for(int i=0;i<m;i++){
//get the sum and the length when it's positive
for(int j=0;j<arr.length;j++){
sum=sum+arr[j];
if(sum>0){
len=j-i+1+m-arr.length;
arrayList.add(len);
}
}
//can be delete
for(int s=0;s<arr.length;s++){
System.out.print(arr[s]+" ");
}
System.out.println();
sum=0;
arr=removeFirstElement(arr);
}
int[] result =new int[arrayList.size()];
for(int k =0;k<arrayList.size();k++){
result[k]=arrayList.get(k);
System.out.print(result[k]+" ");
}
System.out.println();
Arrays.sort(result);
return result[arrayList.size()-1];
}
public static void main (String[] args) throws IOException{
BufferedReader reader =new BufferedReader(new InputStreamReader(System.in));
//read m
String a =reader.readLine();
int m =Integer.parseInt(a);
//read array
String b =reader.readLine();
String[] c =b.split(" ");
int[] arr =new int[m];
for(int i=0;i<m;i++){
arr[i]=Integer.parseInt(c[i]);
}
//use the method
int result =getResult(m, arr);
System.out.println(result);
}
}
将这里如图
注:本文以一个例子来演示广义表的基本操作,含有一个头文件《GList.h》和一个测试源文件《main.cpp》
问题的现象是循环体执行的次数比期望的多了一次。这个问题通常出现在循环条件的判断出现错误导致循环多执行一次的情况下。解决这个问题的方法有多种,具体取决于代码的具体情况。
根据参考资料中的段落1的示例代码,该代码使用for循环生成10个不重复的随机数,并存入数组。该问题描述的是循环体执行的次数比期望的多了一次,具体来说是外层循环的次数多了一次。代码中的外层循环使用的是固定的100次循环,但实际上生成10个不重复的随机数只需要少于100次的循环。因此,要解决这个问题,需要修改外层循环的条件。
以下是修改后的代码示例:
public class Work_03 {
public static void main(String[] args) {
// 定义数组
int[] arr = new int[10];
Random random = new Random();
boolean b = false;
int count = 0;
// 修改外层循环的条件
while (count < 10) {
int temp = random.nextInt(10) + 1;
// 内层循环比较随机数是否与数组数据相同
for (int j = 0; j < arr.length; j++) {
if (temp != arr[j]) {
b = true;
} else {
b = false;
break;
}
}
// 判断是否能将随机数写入数组
if (b) {
arr[count] = temp;
count++;
}
}
// 遍历循环打印数组
for (int a : arr) {
System.out.println(a);
}
}
}
修改后的代码中使用了while循环替代了for循环,并且将外层循环的条件修改为了“count < 10”,即当count变量达到10时退出循环。这样就保证了只会生成10个不重复的随机数。