好的,我再次请求你们的帮助。
我有一个正常的队列实现。但我还想在代码中添加一个方法,该方法将读取用户手动输入的数字数组。然后检查每个项目是否是素数。 如果找到素数,那么它应该输出它。我尝试了一些东西,但它没有输出任何可取的东西。
我尝试找到有关它的信息,但没有成功。
这是我的代码:
Que Class:
class Que{
private int size;
private int front = -1;
private int rear = -1;
private Integer[] queArr;
public Que(int size) { //Definition of the structure size.
this.size = size;
queArr = new Integer[size];
}
public void insert(int item) {
if(rear == size-1) { // case if the structure is full
System.out.println("queue is overflowing");
}
else if(front==-1) {
rear++;
queArr[rear] = item;
front = rear;
}
else {
rear++;
queArr[rear] = item;
}
}
public void delete() {
if(front == -1) { //case if the structure is empty.
System.out.println("queue is underflow");
}
else if(front==rear) { //case to delete the first item in the queue
System.out.println("removing "+queArr[front]);
queArr[front] = null;
front--;
rear--;
}
else {
System.out.println("removing "+queArr[front]);
queArr[front] = null;
for(int i=front+1;i<=rear;i++) {
queArr[i-1]=queArr[i];
}
rear--;
}
}
public void display() {
if(front==-1)
System.out.println("queue is empty");
else
{
System.out.println("queue is:");
for(int i=front;i<=rear;i++) {
System.out.print(queArr[i]+"\t");
}
}
}
public void task(){
//loop through the numbers one by one
for (int n = front; n<=rear; n++) {
boolean prime = true;
//analyzes if n is prime
for (int j = 2; j < n; j++) {
if (n % j == 0 ) {
prime = false;
break; // exit the inner for loop
}
}
//outputs primes
if (prime && n != 1) {
System.out.print(n + " ");
}
}
}
}
和Run类:
import java.util.Random;
import java.util.Scanner;
public class Run {
public static void main(String[] args) {
System.out.println("Queue.");
Scanner scan = new Scanner(System.in);
System.out.println("How much space is needed?");
int size = scan.nextInt();
Que que = new Que(size);
char ch;
do{
System.out.println("\nOptions \n");
System.out.println("1. Insert a new item.");
System.out.println("2. delete an item from the list.");
System.out.println("3. Randomly insert an item in the list.");
//System.out.println("4. task");
int choice = scan.nextInt();
switch(choice) {
case 1: System.out.println("Enter a number!");
que.insert(scan.nextInt());
break;
case 2:que.delete();
break;
case 3: Random rand = new Random();
que.insert(rand.nextInt(size));
break;
case 4: que.task();
}
que.display();
System.out.println("\nDo you want to continue (Type y or n) \n");
ch = scan.next().charAt(0);
}
while(!(ch=='N' || ch=='n'));
}
}
任何想法或指示?