向数组添加元素会提供错误代码。

huangapple go评论58阅读模式
英文:

Adding element to array provides error codes

问题

以下是翻译好的代码部分:

public static void primeFactors(int n) {
    // 创建用于过滤重复项的数组
    List<Integer> primeFactorList = new ArrayList<>();
    // 开始计时以计算程序运行时间
    long startTime = System.nanoTime();

    // 打印分解出的数字2的次数
    System.out.print("该数的素因数为:\n");
    // 下面的while循环在数字为偶数时运行
    while (n % 2 == 0) {
        primeFactorList.add(2);
        n /= 2;
    }

    // 现在n为奇数,因为偶数的循环已经结束
    // 跳过一个元素(注意 i = i + 2)
    for (int i = 3; i <= Math.sqrt(n); i += 2) {
        // 当i能整除n时,打印i并将n除以i
        while (n % i == 0) {
            primeFactorList.add(i);
            n /= i;
        }
    }

    // 处理当'n'是大于2的素数的情况
    if (n > 2) {
        primeFactorList.add(n);
    }
    System.out.print(primeFactorList.stream().distinct().collect(Collectors.toList()));
    float endTime = System.nanoTime();
    float totalTime = endTime - startTime;
    System.out.print("\n程序运行耗时:" + (totalTime / 1000000) + " 毫秒");
}

public static void main(String[] args) {
    System.out.println("这是一个素因数计算器。请输入一个数字:");
    Scanner intN = new Scanner(System.in);
    int nValue = intN.nextInt();
    if (nValue >= 0) {
        int n = nValue;
        primeFactors(n);
    } else {
        System.out.println("您输入的值为负数,请重新启动程序并输入正整数");
    }
}

控制台的错误信息如下:

异常线程 "main" java.lang.UnsupportedOperationException
at java.util.AbstractList.add(AbstractList.java:148)
at java.util.AbstractList.add(AbstractList.java:108)
at com.amitaltman.firstproject.TestingStuff.primeFactors(TestingStuff.java:32)
at com.amitaltman.firstproject.TestingStuff.main(TestingStuff.java:54)
英文:

I am having trouble with my code. I am trying to make a prime factor program, and I want to remove duplicates. However, they always give me an error when I run the following code, and I am confused on why:

public static void primeFactors(int n) {
// Create array to filter out duplicates
List&lt;Integer&gt; primeFactorList = Arrays.asList();
// Start timer to calculate how long the program takes
long startTime= System.nanoTime();
// Print the number of 2s that divide n
System.out.print(&quot;The prime factor(s) of that number:\n&quot;);
// The following is a while loop running when the number is even
while (n % 2 == 0) {
primeFactorList.add(2);
n /= 2;
}
// n is now odd, as the even while loop is over.
// skip one element (Note i = i +2)
for (int i = 3; i &lt;= Math.sqrt(n); i += 2) {
// While i divides n, print i and divide n
while (n % i == 0) {
primeFactorList.add(i);
n /= i;
}
}
// This condition is to handle the case when &#39;n&#39; is a prime number greater than 2
if (n &gt; 2) {
primeFactorList.add(n);
}
System.out.print(primeFactorList.stream().distinct().collect(Collectors.toList()));
float endTime= System.nanoTime();
float totalTime= endTime -startTime;
System.out.print(&quot;\nThis program took &quot; + (totalTime/1000000 + &quot; milliseconds to run&quot;));
}
public static void main(String[] args)
{
System.out.println(&quot;This is a prime factor calculator. Please enter a number: &quot;);
Scanner intN = new Scanner(System.in);
int nValue = intN.nextInt();
if (nValue &gt;= 0){
int n = nValue;
primeFactors(n);
} else {
System.out.println(&quot;Your value is negative, please restart the program and enter a positive integer&quot;);
}
}

The console errors go as followed:

Exception in thread &quot;main&quot; java.lang.UnsupportedOperationException
at java.util.AbstractList.add(AbstractList.java:148)
at java.util.AbstractList.add(AbstractList.java:108)
at com.amitaltman.firstproject.TestingStuff.primeFactors(TestingStuff.java:32)
at com.amitaltman.firstproject.TestingStuff.main(TestingStuff.java:54)

答案1

得分: 1

你不能以那种方式动态增加列表的大小。

使用以下内容进行替换:

List<Integer> primeFactorList = Arrays.asList();

使用以下内容:

List<Integer> primeFactorList = new ArrayList<Integer>();

这将使你的代码正常工作。

示例输出

这是一个质因数计算器。请输入一个数字:
45678
该数字的质因数为:
[2, 3, 23, 331]
该程序运行时间为0.0毫秒
英文:

You can not dynamically increase the size for the list in that way.

Replace below :

List&lt;Integer&gt; primeFactorList = Arrays.asList();

With Below :

List&lt;Integer&gt; primeFactorList = new ArrayList&lt;Integer&gt;();

This will make your code work.

Example Output

This is a prime factor calculator. Please enter a number:                                                                                                   
45678                                                                                                                                                       
The prime factor(s) of that number:                                                                                                                         
[2, 3, 23, 331]                                                                                                                                             
This program took 0.0 milliseconds to run

huangapple
  • 本文由 发表于 2020年10月1日 21:25:15
  • 转载请务必保留本文链接:https://go.coder-hub.com/64156355.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定