I want to create a program that will ask the user to input 5 integers using array and determine all the prime numbers entered. But I have difficulty with it. What seems to be the problem? I use JCreator for this.
import java.util.Scanner;
public class PrimeNumbers{
public static void main (String[] args){
int[] array = new int [5];
Scanner in = new Scanner (System.in);
System.out.println("Enter the elements of the array: ");
for(int i=0; i<5; i++)
{
array[i] = in.nextInt();
}
//loop through the numbers one by one
for(int i=0; i<array.length; i++){
boolean isPrime = true;
//check to see if the numbers are prime
for (int j=2; j<array[i]; j++){
if(array[i]%j==0){
isPrime = false;
break;
}
}
//print the number
if(isPrime)
System.out.println(array[i] + " are the prime numbers in the array ");
}
}
}
You are checking the loop counters, not the values in the array. Try something like
for (int j=2; j<array[i]; j++){
if(array[I]%j==0){
isPrime = false;
break;
}
I haven't tested this.
UPDATE
To print out the results either print each on as it is found, or, copy the prime numbers into an output array and then print that when you have finished the checks. The details will depend on the language you are using.
Please note, you are not using a very efficient detection algorithm; Google for a better one.
You can check all integer numbers until root of the required number
Pseudo code:
for(i=2; i<sqrt(number);i++){
if(number/i===0){
//not prime number
}
}
Find all prime numbers from the array.
package com.myfirstproject;
public class array_Uni_work {
public static void main(String[] args) {
int[] array = {6,48,47,7 , 98,51,87,99,2,0,1,191,157};
// loop through the numbers one by one
for (int i = 0; i < array.length; i++) {
boolean isPrime = true;
if (array[i] == 1)
isPrime = false;
else {
// check to see if the numbers are prime
for (int j = 2; j <= array[i] / 2; j++) {
if (array[i] % j == 0) {
isPrime = false;
break;
}
}
}
// print the number
if (isPrime){
if (array[i] == 0){}
else {
System.out.print(array[i] + " , ");
}
}}
System.out.println(" Are the prime number in the array ");
}
}
public static void main(String[] args) {
int[] array = new int[5];
Scanner in = new Scanner(System.in);
System.out.println("Enter the elements of the array: ");
for (int i = 0; i < 5; i++) {
array[i] = in.nextInt();
}
// loop through the numbers one by one
for (int i = 0; i < array.length; i++) {
boolean isPrime = true;
if (array[i] == 1)
isPrime = false;
else {
// check to see if the numbers are prime
for (int j = 2; j <= array[i] / 2; j++) {
if (array[i] % j == 0) {
isPrime = false;
break;
}
}
}
// print the number
if (isPrime)
System.out.println(array[i] + " is a prime number in the array ");
}
}
Here is more efficient code finding prime number. We only need to check the odd number up to the square root of N, assume the number is greater than 2.
boolean isPrime(int n) {
//check if n is a multiple of 2
if (n%2==0) return false;
//if not, then just check the odds
for(int i=3;i*i<=n;i+=2) {
if(n%i==0)
return false;
}
return true;
}
This is the simplest form of finding the prime numbers from the given array. We can also use scanner by assigning n instead of an array to check whether if it is a prime or non prime from the given input(commented in program).Hope this helps you..!!
public static void main(String[] arg) {
int a[]= {1,2,3,4,5,6,7,8,9,10}; //int n=0 or n=values
int num =0;
String primeNumbers = "";
for (int i = 0; i <= a.length; i++) /*change a.length to n*/
{
int counter=0;
for(num =i; num>=1; num--)
{
if(i%num==0)
{
counter = counter + 1;
}
}
if (counter ==2)
{
//Appended the Prime number to the String
primeNumbers = primeNumbers + i + " ";
}
}
System.out.println("Prime numbers from given array :");
System.out.println(primeNumbers);
}
}
Since you have asked for 5 number explicitly, the code has hardcoded for 5 numbers
import java.util.Scanner;
public class PracticeTest {
public static void main(String args[]) {
int arr[] = new int[5];
Scanner sc = new Scanner(System.in);
System.out.println("Enter 5 numbers");
for (int i = 0; i < 5; i++) {
arr[i] = sc.nextInt();
}
checkPrimeNumbers(arr);
}
public static void checkPrimeNumbers(int arr[]) {
loop1:
for (int j = 0; j < arr.length; j++) {
loop2:
for (int i = 2; i < arr[j]; i++) {
if (arr[j] % i == 0) {
continue loop1;
}
}
System.out.print(arr[j] + " ");
}
}
}
This is the simplest way to accept 'n' integers and display the prime and non prime numbers present in that array. Without using functions
import java.util.Scanner;
// Author Dot-Coin
public class The_Prime {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
System.out.println("Enter the size of the array");
int size=sc.nextInt();
int Primer[]=new int [size];
int Non_Primer[]=new int [size];
int Numbers[]=new int [size];
int counter=0;int j=0,k=0,m=0,n=0;
System.out.println("Enter the numbers ");
for(int i=0;i<size;i++)
Numbers[i]=sc.nextInt();
for(int i=0;i<size;i++)
{
if(Numbers[i]==1||Numbers[i]==0)
{
continue;
}
for(n=1;n<=Numbers[i];n++)
{
if(Numbers[i]%n==0)
counter++;
}
if(counter>2)
{
Non_Primer[k]=Numbers[i];k++;counter=0;continue;
}
if(counter==2)
{
Primer[m]=Numbers[i];m++;counter=0;
}
}
System.out.println("The prime numbers are");
for(k=0;k<Primer.length;k++)
{
if(Primer[k]==0)
{
j++;continue;
}
else
System.out.println(Primer[k]);
}
if(j==Primer.length)
System.out.println("Null");j=0;
System.out.println("The Non prime numbers are ");
for( k=0;k<Non_Primer.length;k++)
{
if(Non_Primer[k]==0)
{
j++;continue;
}
System.out.println(Non_Primer[k]);
}
if(j==Non_Primer.length)
System.out.println("Null");
}}
Related
import java.util.Scanner;
public class PrimeN {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
int a, b;
a = sc.nextInt();
b = sc.nextInt();
while (a < b) {
for (int i = a; i <= b; i++) {
int count = 0;
for (int j = 1; j <= i; j++) {
if (i % j == 0) {
count++;
}
} //count if equals 2 the prime numbers displayed
if (count == 2) {
System.out.println(i);
a++;
}
}
}
}
}
This is what my output looks like. I dont understand why last prime numbers are being repeatedly printed.
What you should probably do is breaking task into steps.
Get the input
satrt finding the prime numbers from 1 to the max
create a list of already found prime numbers
start a loop from 1 to max
each iteration loop trough already found primes and perform number % prime == 0
if none of numbers in prime numbers can fulfils the condition add number to the list
if found number is greater or equal to min, save the index of it (startIndex).
print the input by iterating trough list from startIndex and printing the numbers
this workflow guarantees you will not consider multiplicant of two big prime numbers as prime number with better performance
You missplaced your first statement, your while-loop is a little bit scary, but here your fix:
import java.util.Scanner;
public class PrimeN{
public static void main(String args[]){
Scanner sc = new Scanner(System.in);
int a,b;
a = sc.nextInt();
b = sc.nextInt();
for(int i = a; i <= b; i++){
int count = 0;
for(int j = 1; j <= i; j++){
if(i%j == 0){
count++;
}
}//count if equals 2 the prime numbers displayed
if(count == 2){
System.out.println(i);a++;
}}}}
Found a way to solve the ques.
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int a, b;
a = sc.nextInt();
b = sc.nextInt();
for(int n = a; n <= b; n++){
boolean prime = true;
int i = 2; //1 will be a factor always
while(i <= n/2){
if(n%i == 0){
//is not prime
prime = false;
break;
}i++;
}
if(prime){
System.out.print(n+ " ");
}
}}}
Just remove your while(a<b) around the two for loops and then your code works fine
like this
import java.util.Scanner;
public class PrimeN {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
int a, b;
a = sc.nextInt();
b = sc.nextInt();
// System.out.println("a<b");
int i = a;
while(i<=b)
{
int count = 0;
for (int j = 1; j <= i; j++) {
if (i % j == 0) {
count++;
}
} // count if equals 2 the prime numbers displayed
if (count == 2) {
System.out.println("a" + a + " i:" + i);
a++;
}
i++;
}
}
}
To find out what the actual error is, print out the values of a,b,i and j in each iteration.
I feel I am so close! The output is just outputting true true true or false false false (depending on the length of the array and the user inputs.
I feel this is because of the if/else! For instance, if the number you input first is either true or false it makes all of them that!?
This is supposed to print to the console the numbers in the array, the index of the array numbers, and whether they are prime or not, individually.
Thanks for the help!!
import java.util.Scanner;
import java.util.Arrays;
public class isItPrime {
//main method
public static void main (String[] args) {
//Scanner
Scanner input = new Scanner(System.in);
System.out.println("Enter length of array: ");
int n = input.nextInt();
int[] numbers = new int[n];
System.out.println("Enter " + n +" integers to fill the array: ");
for(int i=0; i<n; i++){
numbers[i] = input.nextInt();
}
System.out.println(Arrays.toString(numbers));
for(int j=0; j<n; j++){
System.out.println(numbers[j] + ": " + j + " -- " + isPrime(numbers));
}
}
public static boolean isPrime(int[] numbers){
boolean Prime = true; //initial boolean value
for (int i = 2; i<numbers.length; i++) {
for (int j=0; j<numbers.length; j++) {
if (numbers[j] == 1 || numbers[j] == 0) {
Prime = false;
}
else if (numbers[j]%i==0){ //function which determines if an int is prime.
Prime = false;
}
else {
Prime = true;
}
}
}
return Prime;
}
}
This is what you need:
public class IsItPrime{
//main method
public static void main(String[] args) {
//Scanner
Scanner input = new Scanner(System.in);
System.out.println("Enter length of array: ");
int n = input.nextInt();
int[] numbers = new int[n];
System.out.println("Enter " + n + " integers to fill the array: ");
for (int i = 0; i < n; i++) {
numbers[i] = input.nextInt();
}
System.out.println(Arrays.toString(numbers));
for (int j = 0; j < n; j++) {
System.out.println(numbers[j] + ": " + j + " -- " + isPrime(numbers[j]));
}
}
public static boolean isPrime(int numbers) {
boolean Prime = true;
if (numbers == 1 || numbers == 0) {
Prime = false;
return Prime;
}
for (int i = 2; i < numbers; i++) {
if (numbers % i == 0) {
Prime = false;
return Prime;
} else {
Prime = true;
}
}
return Prime;
}
}
Only a single integer needs to be passed to the isPrime function.
Also, for processing this integer only a single loop would suffice in the isPrime function.
I have made the required changes.
Assuming you want to return which elements are prime:
public static boolean isPrime(int[] numbers){
boolean prime[] = new boolean[numbers.length]; //initial boolean value
for (int i = 0; i<numbers.length; i++) {
for (int j=2; j<=sqrt(numbers[i]); j++) {
if (numbers[j]%i==0){ //function which determines if an int is prime.
prime[i] = false;
continue;
}
}
prime[i] = true
}
return prime;
}
I'm creating a prime array and whichever is prime, I'm making its position in the array true, and i continue with the next element.
Also, for prime, you have to check until square root of the number for the sake of efficiency.
For example, if you want to check if 10 is prime, it is better to iterate until sqrt(10)=3.2.
Your biggest problem is your isPrime() method should calculate if a particular number is prime, not analyse an array of numbers.
Try this:
public static boolean isPrime(int number){
// return true if prime
}
And call it like this:
System.out.println(numbers[j] + ": " + j + " -- " + isPrime(number[j]));
Altered method to return string i.e, "Prime" or "Not Prime".
public static String isPrime(int numbers) {
if (numbers == 1 || numbers == 0) {
return "Not Prime";
}
for (int i = 2; i < numbers; i++) {
if (numbers % i == 0) {
return "Not Prime";
}
}
return "Prime";
}
This program asks for the user to input 10 numbers and is converted into an int array. If the array is lucky (contains the numbers 7, 13, or 18) then it prints out the sum of all the numbers in the array. If it does not contain those then it is false and it only prints the sum of all the even numbers.
How do I correctly ask for this input? How do I get the sum of the even numbers in the array? Is any of the other code incorrect?
import java.util.Scanner;
public class FunArrays {
public static void main(String[] args) {
// until you do user input, you should test your methods using "test" as the input.
int[] test = {1,2,3,4,5,6,7};
luckyNumber1 = {7};
luckyNumber2 = {13};
luckyNumber3 = {18};
int[] a=new int[9];
Scanner sc=new Scanner(System.in);
System.out.println("Please enter numbers...");
for(int j=0;j==9;j++)
a[j]=sc.nextInt();
}
public static int sum(int [ ] value) {
int i, total = 0;
for(i=0; i<10; i++)
{
total = total + value[ i ];
}
return (total);
}
public static int sumOfEvens (
public static boolean isLucky (int[] array) {
if ( (int == luckyNumber1) || (int == luckyNumber2) || (int == luckyNumber3 )
return true;
else
return false
}
// write the static methods isLucky, sum, and sumOfEvens
}
You have an array of size 9. Instead it should be of size 10. So, Change the initialization to
int[] a=new int[10];
Use modulo operator % or remainder operator in Java to find out even or odd numbers.
int evenSum = 0;
for(int j=0;j<a.length;j++){
if(a[j]%2 == 0){
//even numbers
evenSum = evenSum + a[j];
}else{
//odd numbers
}
}
return evenSum;
int[] a=new int[9];
Scanner sc=new Scanner(System.in);
System.out.println("Please enter numbers...");
for(int j=0;j==9;j++)
a[j]=sc.nextInt();
}
There's something wrong with your loop, it should be
for (int j = 0; j < 9; j++)
With this fix it should correctly prompt the users for 9 numbers. Change to 10 for the array and the loop it would takes in 10 number.
Sum of evens
static int sumOfEvens(int array[]) {
int sum = 0;
for(int i = 0; i < array.length; i++>) {
if(array[i] % 2 == 0)
sum += array[i];
}
return sum;
}
Input
for(int j = 0; j < a.length; j++)
a[j] = sc.nextInt();
import java.util.Scanner;
public class MyMain1 {
public static void main(String[] args) {
// until you do user input, you should test your methods using "test" as
// the input.
int[] luckyNumbers = { 7, 13, 18 };
int[] a = new int[10];
Scanner sc = new Scanner(System.in);
System.out.println("Please enter numbers...");
for (int j = 0; j <= 9; j++) {
a[j] = sc.nextInt();
}
sc.close();
boolean sumAll = false;
for (int i : a) {
for (int j : luckyNumbers) {
if (i == j) {
sumAll = true;
break;
}
}
if(sumAll) {
break;
}
}
if (sumAll) {
System.out.println("Summing all : " + sumAll(a));
} else {
System.out.println("Summing Only Even : " + sumEven(a));
}
}
public static int sumAll(int[] value) {
int total = 0;
for (int j : value) {
total = total + j;
}
return total;
}
public static int sumEven(int[] value) {
int total = 0;
for (int j : value) {
if (j % 2 == 0) {
total = total + j;
}
}
return total;
}
}
I'm trying to solve a problem where I need to find all the even numbers only. I need to input 5 numbers, and if none of the numbers are even I want to print Even number not found in array.
So my problem is when I iterate through the for-loop, my code prints Even number not found in array. It prints for each non-even number, which is not what its suppose to do obviously. I need some kind of hint. This is not homework btw, it is a problem found on Programmr.com. Here is my code:
import java.util.Scanner;
public class ArrayEven {
public static void main(String args[]) {
#SuppressWarnings("resource")
Scanner scanner = new Scanner(System.in);
int x, arr[] = new int[5];
for (int i = 0; i < arr.length; i++) {
arr[i] = scanner.nextInt();
if (i == 4)
break;
}
for (int i = 0; i < arr.length; i++) {
x = arr[i] % 2;
if (x == 0) {
System.out.println(arr[i]);
}
else if (x != 0) { //this is obviously wrong. Do I need another for-loop for this?
System.out.println("Even number not found in array.");
}
}
}
}
You can use a boolean here,
Initialize boolean variable with false
if you found any even than set the boolean as true
and check that boolean in your if condiion.
Example :
boolean isAvailble = false;
...
// Some code
...
for (int i = 0; i < arr.length; i++) {
x = arr[i] % 2;
if (x == 0) {
System.out.println(arr[i]);
isAvailble = true;
}
}
if (! isAvailable) {
System.out.println("Even number not found in array.");
}
public static void main(String args[]) {
#SuppressWarnings("resource")
Scanner scanner = new Scanner(System.in);
int x, arr[] = new int[5];
for (int i = 0; i < arr.length; i++) {
arr[i] = scanner.nextInt();
if (i == 4)
break;
}
boolean evenFound = false;
for (int i = 0; i < arr.length; i++) {
x = arr[i] % 2;
if (x == 0) {
System.out.println(arr[i]);
evenFound = true;
}
}
if(!evenFound){
System.out.println("Not found");
}
}
I'm writing a program that takes 10 numbers as input and displays the mode of the numbers using parallel arrays and a method that takes an array of numbers as a parameter and returns the value that appears most often in the array. PROBLEM: However, when I run my program it has absolutely no output, also, I am not sure how to implement the parallel arrays.
Does anyone know?
Thank you.
import java.util.Scanner;
public class Mode {
public static void main(String[] args) {
}
public int computeMode(int[] nums) {
Scanner scanner = new Scanner(System.in);
int maxValue = -1;
int maxCount = 0;
int x = 0;
//count how many times nums[i] appears in array
System.out.println("Enter 10 numbers: ");
for (int i = 0; i < 10; i++) {
try { //try catch exception to catch decimal inputs as well as more /less than 10 integers
x = scanner.nextInt();
} catch (Exception e) {
System.out.println("Invalid input! Please reenter 10 integer values.");
scanner = new Scanner(System.in);
i = -1;
continue;
}
for (i = 0; i < nums.length; i++) {
int count = 0;
for (int j = 0; j < nums.length; j++) {
if (nums[j] == nums[i]) {
count++;
}
}
if (count > maxCount) {
maxValue = nums[i];
maxCount = count;
System.out.println("The mode is: " + maxValue);
}
}
}
return maxValue;
}
}
The main function is empty, so it does not anything,
and the function doesn't need any parameter, because you read the numbers with the scanner
I think you need this:
import java.util.Scanner;
class Mode {
public static void main(String[] args) {
computeMode();
}
public static void computeMode(){
int nums[]=new int[10];
Scanner scanner = new Scanner(System.in);
int maxValue = -1;
int maxCount = 0;
int x = 0;
//count how many times nums[i] appears in array
System.out.println("Enter 10 numbers: ");
for (int i = 0; i < 10; i++) {
try { //try catch exception to catch decimal inputs as well as more /less than 10 integers
x = scanner.nextInt();
nums[i]=x;
}
catch (Exception e) {
System.out.println("Invalid input! Please reenter 10 integer values.");
i =i -1;
scanner.nextLine();
continue;
}
}
for (int i = 0; i < nums.length; i++) {
int count = 0;
for (int j = 0; j < nums.length; j++) {
if (nums[j] == nums[i]) {
count++;
}
}
if (count > maxCount) {
maxValue = nums[i];
maxCount = count;
}
}
System.out.println("The mode is: " + maxValue);
}
}
The code writes x, but never reads it; reads nums, but never writes it; and implements computeMode, but never calls it.