如何使用扫描仪类在数组中显示质数

问题描述

我最近开始学习Java。我的学校教给我们这种奇怪的方式,我在很多地方都没有见过。我在这里找不到任何问题,但是代码无法正常工作。请指出这里有什么问题。这是我编写的代码

import java.util.*;
class Prime_array_attempt_infinity
{
    public static void main ()
    {
        Scanner sc= new Scanner (system.in);
        int i,j,counter=0,last;
        int arr[]= new int [10];
        System.out.println("Enter the values");
        for (i=0; i<10;i++)
        {
            arr[i]= sc.nextInt();
        }
        for (i=0; i<10; i++)
        {
            last = arr[i];
            for (j=2;j<last;j++)
            {
                if(arr[i]%j==0)
                counter++;
                
            }
        if (counter == 0)
        {
            System.out.println(arr[i]+" is a Prime Number");
           
        }
        }
        
        
    }
            
            
}
    


                
            
                    
            
        

解决方法

args方法缺少main,并且每次在for for内循环之前都需要将counter重置为零(根据定义,1也不是质数: )):

import java.util.*;
class Prime_array_attempt_infinity
{
public static void main (String[] args)
{
    Scanner sc= new Scanner (System.in);
    int i,j,counter=0,last;
    int arr[]= new int [10];
    System.out.println("Enter the values");
    for (i=0; i<10;i++)
    {
        arr[i]= sc.nextInt();
    }
    for (i=0; i<10; i++)
    {
       
        last = arr[i];
    
        if(last <= 1)continue;

        counter = 0;
        for (j=2;j<last;j++)
        {
            if(arr[i]%j==0)
                counter++;

        }
        if (counter == 0)
        {
            System.out.println(arr[i]+" is a Prime Number");

        }
    }


}


}

输出:

Enter the values
1
2
3
4
5
6
7
8
9
10
2 is a Prime Number
3 is a Prime Number
5 is a Prime Number
7 is a Prime Number
,

我想您的代码无法运行。

您需要将main方法替换为

public static void main(String[] args) {
}

并在其中粘贴所有代码。像这样

public static void main(String[] args) {
    Scanner sc= new Scanner (System.in);
    int i,last;
    int arr[]= new int [10];
    System.out.println("Enter the values");
    for (i=0; i<10;i++)
    {
        arr[i]= sc.nextInt();
    }
    for (i=0; i<10; i++)
    {
        last = arr[i];
        for (j=2;j<last;j++)
        {
            if(arr[i]%j==0)
                counter++;

        }
        if (counter == 0)
        {
            System.out.println(arr[i]+" is a Prime Number");

        }
    }
}

然后,您可以运行您的代码段。关于寻找的算法,参见例如example algorithm