In: Computer Science
how to get this to not consider 0, 1 and negative integers as prime. maybe using a "nested loop" or more than one loop?
//TestCode.java import java.util.Scanner; public class TestCode { public static void main(String[] args) { // Creating scanner object Scanner scan = new Scanner(System.in); boolean isPrime; int x; // Declaring an array with 10 ints int arr[] = new int[10]; // Reading values from user System.out.println("Enter 10 integer values for array:"); for(int i = 0;i<arr.length;i++){ arr[i] = scan.nextInt(); } // Looping through each value in array for(int i = 0;i<arr.length;i++){ x = arr[i]; // Assuming x is prime isPrime = true; // Loop through 2 to x-1 for(int j = 2;j<x;j++){ // if x is divisible by any of j if(x%j == 0) { // Then setting isPrime to false isPrime = false; } } // Printing value of x if it is a prime if(isPrime){ System.out.println(x); } } } }
import java.util.Scanner; public class TestCode { public static void main(String[] args) { // Creating scanner object Scanner scan = new Scanner(System.in); boolean isPrime; int x; // Declaring an array with 10 ints int arr[] = new int[10]; // Reading values from user System.out.println("Enter 10 integer values for array:"); for (int i = 0; i < arr.length; i++) { arr[i] = scan.nextInt(); } // Looping through each value in array for (int i = 0; i < arr.length; i++) { x = arr[i]; // Assuming x is prime isPrime = x > 1; // Loop through 2 to x-1 for (int j = 2; j < x; j++) { // if x is divisible by any of j if (x % j == 0) { // Then setting isPrime to false isPrime = false; } } // Printing value of x if it is a prime if (isPrime) { System.out.println(x); } } } }