Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
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.
package arrays;
import java.util.Scanner;
public class Examples {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in) ;
System.out.println("Total numbers : ");
int n = sc.nextInt();
boolean isPrime =true;
int result =0;
System.out.println("Enter the Numbers : ");
int [] numbers = new int[n];
for(int i=0;i<n;i++) {
numbers[i]=sc.nextInt();
}
for(int i=0;i<n;i++) {
for(int j=2;j*j<numbers[i];j++) {
if(numbers[i]%j ==0) {
isPrime =false ;
break;
}
}
}
if(isPrime) {
System.out.println("The Prime Numbers : " +numbers[i]);
}
}
}
You should put the isPrime() inside the outer loop as below -
System.out.println("The Prime Numbers : ");
for(int i=0;i<n;i++) {
isPrime =true; // setting it to true before checking for every numbers
for(int j=2;j*j<numbers[i];j++) {
if(numbers[i]%j ==0) {
isPrime =false ; // will become false only when not an prime
break;
}
}
// isPrime will remain true if numbers[i] is a prime number. So print the prime number
if(isPrime) {
System.out.println(numbers[i]+" ");
}
}
You code had few errors -
if(isPrime) {
System.out.println("The Prime Numbers : " +numbers[i]);
}
Firstly, the above piece of code wouldn't work, since the scope of i is limited only to the for() loop. Even if i was declared outside the for loop, the number that would have been printed would always have been last number (if a prime existed in the user inputted number). That is not we want.
So, print the numbers whenever you verify that a number is not prime. After you complete every inner loop, check the boolean isPrime and if it is true, we know that the number we are currently checking(numbers[i]) is surely a prime. So print the number there itself.
Hope this helps !
The following code snippet fixes all the issues and checks only odd numbers in the loop:
for (int i = 0; i < n; i++) {
isPrime = numbers[i] % 2 == 1;
for (int j = 3; isPrime && j * j <= numbers[i]; j += 2) {
if (numbers[i] % j == 0) {
isPrime = false;
}
}
if (isPrime && numbers[i] > 1) {
System.out.println("The Prime Numbers : " + numbers[i]);
}
}
You should also take into account that 0 and 1 are NOT primes.
You need to check isPrime in outer loop
for(int i=0;i<n;i++) { // This loops for every number
//inner both loops for check the number is prime
boolean isPrime =true;
for(int j=2;j*j<numbers[i];j++) {
if(numbers[i]%j ==0) {
isPrime =false ;
break;
}
}
if(isPrime) {
System.out.println("The Prime Numbers : " +numbers[i]);
}
}
Related
I need to program a lottery simulator and basically everything works fine but I have one small problem at the end of the problem. There are 2 Arrays(i need to work without Array Lists) which get compared. The generated winning numbers and the numbers entered by the user. I succeeded in showing what numbers are the right guesses. But what doesn't work is showing HOW MANY guesses were correct. I tried System.out.println("You guessed this many numbers right: "+intArray.length[i] but this didn't work. Is there any way to show the exact number of how many numbers were guessed right? Thanks for any help in advance
for (int i=0; i< intArray.length;i++){
for (int j=0; j< ownArray.length;j++){
if (intArray[i] == ownArray[j]){
System.out.println("Your following guess was correct: "+intArray[i]);
Just use a count variable
public static void main(String[] args) {
int[] intArray = {1,2,4,5};
int[] ownArray = {1,0,2,7};
int count = 0;
System.out.println("Your following guesses were correct: ");
for (int i = 0; i < intArray.length; i++){
for (int j = 0; j < ownArray.length; j++){
if (intArray[i] == ownArray[j]){
System.out.print(intArray[i] + " ");
count++;
}
}
}
System.out.println("\nNo. of correct guesses: " + count);
}
Output:
Your following guesses were correct:
1 2
No. of correct guesses: 2
This is actually quite simple to do if your lottery numbers are positive numbers. It is more involved if the numbers can be negative. The basic algorithm is to compare lottery numbers one by one against all the player's guesses repeatedly. If there is a match then we record -1 in the user guess array and increment a counter to track the number of correct entries.
Some code will make this clearer:
public class LotteryNumbers {
public static void main(String[] args) {
int[] lotteryNumbers = {1,2,3,4,5,6};
int[] userGuess = {1,2,3,4,8,9};
int correct = 0;
for(int i=0; i<lotteryNumbers.length; i++) {
for(int j=0; j<userGuess.length; j++) {
if( userGuess[j] == lotteryNumbers[i]) {
userGuess[j] = -1; // 'eliminate' this guess for checking
correct++;
break;
}
}
}
System.out.println("Number of correct numbers = " + correct);
}
}
Outputs:
Number of correct numbers = 4
This works because the algorithm strikes out matches in the player's guesses and guards against future matching next time through the loop. You can imagine that what we are actually doing is striking off numbers in the player's guess that match against the lottery numbers.
I'm kind of a newbie at Java, and not very good at it. It's a trial and error process for me.
I'm working on a Java program to output the amount of primes in an array. I can get it to output the primes, but I want to also output the quantity of primes. I tried to add each prime to an array list titled "primes" then return "primes.size()" at the end of my program. It doesn't work as intended. The count is actually off. When I create an array of 5 numbers, it outputs 3 primes, 2, 3, and 5. But then it says I have 4 primes. I think it might be counting 1 as a prime. Because when I create an array of 20, the prime numbers output 2,3,5,7,11,13,17 and 19. Then it says the total prime numbers = 9. It should be 8 though.
Here's my code
public class Prime {
public static void main(String[] args) {
int index = 0;
Scanner scan = new Scanner(System. in );
System.out.println("How big would you like the array? ");
int num = scan.nextInt();
int[] array = new int[num];
ArrayList < Integer > primes = new ArrayList < Integer > ();
//System.out.println("How Many threads? ");
//int nThreads = scan.nextInt(); // Create variable 'n' to handle whatever integer the user specifies. nextInt() is used for the scanner to expect and Int.
//Thread[] thread = new Thread[nThreads];
for (int n = 1; n <= array.length; n++) {
boolean prime = true;
for (int j = 2; j < n; j++) {
if (n % j == 0) {
prime = false;
break;
}
}
if (prime) {
primes.add(n);
}
if (prime && n != 1) {
System.out.println(n + "");
}
}
System.out.println("Total Prime numbers = " + primes.size());
System.out.println("Prime Numbers within " + array.length);
}
}
Forgive the sloppiness of it. I actually plan on adding multithreading to it, but I wanted to get this down first.
Any help would be greatly appreciated. Thanks.
You have included 1 in your array of primes, because you started the n for loop at 1. You don't print it because of the final if statement, but it's there in the ArrayList.
Start your n for loop with n = 2. As a consequence, you won't need the final if statement, because n won't be 1 ever. You could print the prime at the same time as you add it to the ArrayList.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I can't get this code to align correctly. I need it to display in 5 rows of ten, aligned neatly. This is what i have, please help!
import java.util.Scanner;
public class PrimeNumbers {
public static void main(String...args) { //start main method
Scanner sc = new Scanner(System. in ); //renamed Scanner to sc
int a = 1; // first prime number
int b = 227; // 50th prime number
System.out.println(" ");
for (int i = a; i <= b; i++) //this is the primer for the prime number formula
{
boolean isPrime = true; //sets the statement to true
if (isPrime) for (int j = 2; j <= i; j++) //formula to get the prime
{
if (i != j && i % j == 0) //formula checking prime
isPrime = false; //sets statement to false
}
if (isPrime) {
System.out.print(i + " "); //if true it prints prime number
System.out.printf("\n "); //if false it prints a dash
}
}
} //end of main method
} //end of class
You can do it using a counter variable which you will increment once you print a prime number.If counter%10 returns 0 then you can add a new line.
//initialize counter with 0
...
if (isPrime)
{
System.out.print(i+" ");//if true it prints prime number
counter++;
if(counter%10==0)
System.out.println();//it will add a new line
}
...
This is what I have so far. I am supposed to write this code with a For loop and if/else statement, but /i am stuck on how to do it properly. It would be nice if someone can tell me how to properly use a For loop and if/else statement together instead of giving the answer:
import java.util.*;
public class SumEvenOdd
{
public static void main(String []args)
{
Scanner keyboard= new Scanner(System.in);
int counter;
int i= 0;
int num=0;
int sumOdd= 0;
int sumEven= 0;
System.out.println("Enter integers other then Zero: ");
num=keyboard.nextInt();
System.out.println("The numbers you entered are: ");
for (i =num; i !=0; i=i)
{
if (i % 2 == 0)
sumEven = sumEven + i;
else
sumOdd = sumOdd + i;
i = keyboard.nextInt();
}
System.out.println("Even sum: " + sumEven);
System.out.println("Odd sum: " + sumOdd);
}
}
Your loop never executes because your loop condition is false to begin with:
for (i =num; i !=0; i=i) // i already equals 0 so i != 0 equates to false
You also aren't incrementing or decrementing with i=i so even if your condition was true you'd be stuck in an infinite loop. Use i++ to increment the value of i by 1 in each iteration of your for loop.
Also, you're only taking in one number from the user. One simple way of handling this would be to first ask the user how many numbers they want to enter first, then use that input to loop that many times asking for the numbers to sum. For example:
System.out.println("How many numbers do you want to enter? ");
num=keyboard.nextInt();
int[] addThese = new int[num]; // create an array of size num to store numbers
for(int i = 0; i < num; i++) {
System.out.print(": ");
addThese[i] = keyboard.nextInt();
}
// now use your for loop to iterate over addThese[] and find your sums
...
EDIT
You've confused yourself (and me) with your print statements and lack thereof. Your program runs fine but I don't think you're realizing it because of this.
Add something like this inside your loop so you know it's waiting for input:
if (i % 2 == 0)
sumEven = sumEven + i;
else
sumOdd = sumOdd + i;
System.out.print(": "); // <-- let the user know you're expecting more input
i = keyboard.nextInt();
You can use an array like I used above to store the user input so you actually can tell the user what numbers they entered.
In your application you do not need a for loop as you are breaking the loop as long you dont enter 0.
for loops is used to iterate through collections (for each loop) or iteratively increment a counter till it satisfies the break(classic for loop).
A do while(i!=0) loop would be more appropriate in your scenario.
If you want the answer in while loops
import java.util.*;
/*
EXPLANATION
Question: write a program that reads a set of integers and tells the sum of the even and odd numbers
First: Initialize 4 variables(all integers)
Second: Take input and print title
Third: Take a while loop that will run when i is smaller than a
Fourth: take inputs of the numbers and check for condition od or even and add the numbers
Fifth: Break the while loop if input =
*/
public class EvenOddSum
{
public static void main(String[]args)
{
//initializing variables
int InputNums = 0, OddNums = 0, EvenNums = 0, loopingVar = 0, PrintAmount;
//initializing scanner class
Scanner scanner = new Scanner(System.in);
//Input using Scanner
System.out.print("How many numbers you want to input: ");
PrintAmount = scanner.nextInt();
//Loop to execute if PrintAmount is bigger than or equal to The loop Variable
while(loopingVar <= PrintAmount)
{
//increase Loop Variable by 1 if it is smaller than PrintAmount
loopingVar++;
//The input which will be sorted into odd or even
System.out.print("Please input a number : ");
InputNums = scanner.nextInt();
//Conditional statements to Sort Input into Odd or even
if (InputNums % 2 == 0)
{
//store input numbers into OddNums var if it is not divisible by 2
OddNums = OddNums + InputNums;
}
else
{
//store input numbers into EvenNums var if it is divisible by 2
EvenNums = EvenNums + InputNums;
}
if(loopingVar == PrintAmount)
{
//If the loop variable is equal to the print amount the break will end the loop
break;
}
}
//if the condition is true the sums are printed and the code is stopped
if (loopingVar == PrintAmount)
{
System.out.println("Sum of even numbers is : " + OddNums);
System.out.println("Sum of odd numbers is : " + EvenNums);
System.exit(0);
}
//if InputNums is smaller than 0 there has been some error in the code
if (InputNums < 0)
{
System.out.print("Invalid input");
System.exit(0);
}
}
}
Scanner input = new Scanner(System.in);
int num;
int i;
int x = 0;
int y = 0;
System.out.print("How many numbers you want to input: ");
i = input.nextInt();
for (;;) {
i--;
System.out.print("Please input a number : ");
num = input.nextInt();
if (num % 2 == 0) {
x = x + num;
} else {
y = y + num;
}
if (num < 0) {
System.out.print("Inivald input");
System.exit(0);
}
if (i == 0) {
System.out.println("Sum of even numbers is : " + x);
System.out.println("Sum of odd numbers is : " + y);
System.exit(0);
}
}
import java.util.Scanner;
public class Loop {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
// printing the sum of even and odd number input from the user
int evensum = 0 ;
int oddsum = 0 ;
System.out.println("Enter the number:");
for(int n1= sc.nextInt(); n1>0; n1=sc.nextInt()) {
if(n1 % 2 == 0) {
evensum+=n1 ; // evensum = evensum + n1 ;
}
else {
oddsum+=n1 ; // oddsum = oddsum + n1 ;
}
System.out.println("Sum of even number is :"+evensum);
System.out.println("Sum of odd number is :"+oddsum);
// asking for continuing y or n?
System.out.println("Do you want to continue ? yes = 1 or no = 0");
int choice = sc.nextInt();
if(choice==1) {
System.out.println("Enter the number :");
}
else {
System.out.println("End");
break;
}
}
System.out.println("Sum of even number is :"+evensum);
System.out.println("Sum of odd number is :"+oddsum);
}
}
Write a program that reads a list of 10 values from the user. Put the values in an array. The program should read the array and then calculate and display the average of the even input values and the average of the odd input values. This should be done using objects, methods, and a tester class.
I cannot figure out why I am receiving the error:
bad operand types for binary operator.
I do not know what to change. I know something is wrong with my mod (%).
Here is what I have so far for my Average class:
public class Average
{
private int[] numbers = new int[10];
double aveEven, aveOdd,sumEven=0,sumOdd=0;
int oddCounter=0, evenCounter=0;
public Average(int[] n)
{
numbers = n;
if (numbers % 2 == 0)/something is wrong here/
{
evenCounter++;
sumEven+=n;
}
else
{
oddCounter++;
sumOdd+=n;
}
}
public void aveEven()
{
for (int i = 0; i < numbers.length; i++)
{
aveEven = sumEven/evenCounter;
System.out.println("The even average is: " + aveEven);
}
}
public void aveOdd()
{
for(int i = l; i < numbers.length; i++)
{
aveOdd = sumOdd/oddCounter;
System.out.println("The odd average is: " + aveOdd);
}
}
}
For the AverageTester class I have the following:
import java.util.Scanner;
public class AverageTester
{public static void main(String[] args)
{
int[] integer = new int[10];
Scanner input = new Scanner(System.in);
for(int i=0 ; i < 10 ; i++)
{
System.out.print("Please enter a number : ");
integer[i] = input.nextInt();
}
Average example = new Average(integer);
example.aveOdd();
}
}
Also, If you see anything else that could be wrong, please let me know.
Thank you.
numbers is an array, so numbers % 2 is invalid. You should loop over the array and use the % operator on the elements of the array. The += operator should also be applied on a element of the array (i.e. numbers[i]) and not the entire array.
numbers = n;
for (int i = 0; i < numbers.length; i++) {
if (numbers[i] % 2 == 0) {
evenCounter++;
sumEven+=numbers[i];
} else {
oddCounter++;
sumOdd+=numbers[i];
}
}
As for aveEven and aveOdd, since you already compute the sums in the constructor (or at least it seems like that's what you intended to do), you don't need a loop in these methods.
EDIT :
I originally assumed you intended to calculate the average of the numbers in even positions in the array and the average of the numbers in odd positions. After reading the question again, I think the odd/even refers to the numbers themselves, so I changed the code accordingly.
Numbers is an array and comparing an array to an int doesn't work, you could do something like this (depending on your logic):
for(int number : numbers){
if(number % 2 == 0){
evenCounter++;
sumEven += n;
}else{
oddCounter++;
sumOdd += n;
}
}
Few Mistakes
1.) if (numbers % 2 == 0), numbers is an array, use index here and loop. like this if (numbers[i] % 2 == 0).
2.) sumEven += n;, again n is an array here, need to use index.
3.) for (int i = l ; i < numbers.length ; i++) {, you have used l instead of 1.