我是初学者编码器,我试图找到n的最大值,但我遇到了麻烦。我试图使用for循环来搜索我创建的数组的每个元素,但代码每次都返回0。这种方法是否正确?我已经尝试将n的值输入到数组中,但我不确定这是否是解决此目标的正确方法。
import java.util.*;
public class CollatzConjecture {
private static int max;
public CollatzConjecture(int maximum){
int max=maximum;
}
public static void main(String[] args) {
ArrayList<Integer> arr = new ArrayList<Integer>();
Scanner scan = new Scanner(System.in);
System.out.print("Type an integer: ");
int n = scan.nextInt();
int count = 0;
while(n>1)
{
if(n%2 == 0)
{n = n/2;}
else
{n = 3*n + 1;}
System.out.println(n + " ");
count++;
arr.add(n);
arr.get(n);
}
for(int i = 0; i<arr.size()-1; i++)
{
if(arr.get(i) > max)
{
int max = arr.get(i);
}
}
System.out.println(arr);
System.out.println("Terminated after " + count + " steps");
}
}
答案 0 :(得分:0)
因此,如果我正确理解您的问题,您只是想在数组中找到最大值?如果是这样的话:
int max = arr.stream().max(Integer::compare).get();
或
int max = arr.get(0);
for (int i = 1; i < arr.size(); i++)
max = Integer.max(max, arr.get(i));
答案 1 :(得分:0)
做了一些改变,但是你走了:
public class CollatzConjecture {
private int max;
public CollatzConjecture() {
ArrayList<Integer> arr = new ArrayList<Integer>();
Scanner scan = new Scanner(System.in);
System.out.print("Type an integer: ");
int n = scan.nextInt();
int count = 0;
while (n > 1) {
if (n % 2 == 0) {
n = n / 2;
} else {
n = 3 * n + 1;
}
System.out.println(n);
count++;
arr.add(n);
}
for (int i = 0; i < arr.size(); i++) {
if (arr.get(i) > max) {
this.max = arr.get(i);
}
}
System.out.println(arr);
System.out.println("Largest value of n: " + this.max);
System.out.println("Terminated after " + count + " steps");
scan.close();
}
public static void main(String[] args) {
new CollatzConjecture();
}
}