Question

In: Computer Science

I have to code the assignment below. I cannot get the program to work and I...

I have to code the assignment below. I cannot get the program to work and I am not sure what i am missing to get the code to work past the input of the two numbers from the user. My code is listed under the assignment details. Please help!

Write a Java program that displays the prime numbers between A and B. Inputs: Prompt the user for the values A and B, which should be integers with B greater than A. Outputs: The output will be all the prime numbers between A and B. Each line of output will contain five prime numbers except for the last line, which may have less depending on the total number of primes identified. Code the program in Eclipse using a loop to calculate all prime numbers between A and B. Use the code below to determine if a number is prime. Each line of output will contain 5 prime numbers except the last line.

boolean isPrime = true

for (int divisor = 2; divisor <= number / 2; divisor++) {
           if (number % divisor == 0) {
              
           isPrime = false;
           break;

Test your program and it should display all prime numbers between 101 and 200.  

My Code

import java.util.Scanner;
public class Ch5Project {
   public static void main(String[] args) {
Scanner input = new Scanner(System.in);
      
   System.out.print("Enter the value of A: ");
       int number1 = input.nextInt();
   System.out.print("Enter the value of B: ");
       int number2 = input.nextInt();
      
   final int NUMBER_OF_PRIMES = 21;
   final int NUMBER_OF_PRIMES_PER_LINE = 4;
   int count = 100;
   int number = 102;
  
   while (count < NUMBER_OF_PRIMES) {
       boolean isPrime = true;
      
       for (int divisor = 2; divisor <= number / 2; divisor++) {
           if (number % divisor == 0) {
              
           isPrime = false;
           break;   
           }
       }
     if (isPrime) {
           count++;
          
           if (count % NUMBER_OF_PRIMES_PER_LINE == 0) {
               System.out.println(number);
           }
           else
               System.out.print(number + " ");
       }
      
       number++;
           }
       }
}

Solutions

Expert Solution

Errors in the given code

  • In the question it is asked to list prime numbers between two integers
  • But in the code,it is manually fiound NUMBER_OF_PRIMES = 21.
  • The program should itself able to list and find number of primes
  • In the given code, it is tried to find prime between 100 and 200.
  • Program should have been generalized to find primes between any two numbers
  • count < NUMBER_OF_PRIMES evaluates 100<21 which is false.
  • The loop never executes and print nothing

Corrected code

//importing Scanner class for reading user input
import java.util.Scanner;
public class Ch5Project {
    public static void main(String[] args) {
        //creating Scanner object to read user input
        Scanner input = new Scanner(System.in);
        //prompt user to enter two integers and read it using nextInt() method
        System.out.print("Enter the value of A: ");
        int number1 = input.nextInt();
        System.out.print("Enter the value of B: ");
        int number2 = input.nextInt();
        //define constant NUMBER_OF_PRIMES_PER_LINE and set it value 5
        final int NUMBER_OF_PRIMES_PER_LINE = 5;
        //initialize number with number1 and count with 0
        int number = number1, count = 0;
        //loop iterate through each number from number1 to number2
        while (number < number2) {
            //set boolean isPrime to true
            boolean isPrime = true;
            //iterate through 2 to half of the number
            for (int divisor = 2; divisor <= number / 2; divisor++) {
                //if number has any factor,then it is not a prime
                if (number % divisor == 0) {
                    isPrime = false;
                    break;
                }
            }
            //if number doesn't have any factor,then increment count by 1 and print 
            //the number
            if (isPrime) {
                count++;
                //if count is a multiple of 5,then print output in new line
                if (count % NUMBER_OF_PRIMES_PER_LINE == 0) {
                    System.out.println(number);
                } 
                //otherwise print in same line
                else
                    System.out.print(number + " ");
            }
            number++;
        }
    }
}

Screen shot of the code

Screen shot of the output


Related Solutions

I cannot get this code to run on my python compiler. It gives me an expected...
I cannot get this code to run on my python compiler. It gives me an expected an indent block message. I do not know what is going on. #ask why this is now happenning. (Create employee description) class employee: def__init__(self, name, employee_id, department, title): self.name = name self.employee_id = employee_id self.department = department self.title = title def __str__(self): return '{} , id={}, is in {} and is a {}.'.format(self.name, self.employee_id, self.department, self.title)    def main(): # Create employee list emp1...
How would I get this started: Code a logic program that uses a for loop to...
How would I get this started: Code a logic program that uses a for loop to call your method 5 times successively on the values 1 through 5. (i.e. it would display the val and it’s square…)
Question: Can I get the code in Java for this assignment to compare? Please and thank you....
Question: Can I get the code in Java for this assignment to compare? Please and thank you. Can I get the code in Java for this assignment to compare? Please and thank you. Description Write a Java program to read data from a text file (file name given on command line), process the text file by performing the following: Print the total number of words in the file. Print the total number of unique words (case sensitive) in the file. Print...
How would I get this java code to work and with a main class that would...
How would I get this java code to work and with a main class that would demo the rat class? class rat { private String name; private String specialAbility; private int TotalHealth; private int shieldedHealth; private int cooldown; public rat() { } public rat(String n,String SA,int TH,int SH,int cd) { name=n; specialAbility=SA; TotalHealth=TH; shieldedHealth=SH; cooldown=cd; } public void setname(String n) { name=n; } public String getname() { return name; } public void setability(String SA) { specialAbility=SA; } public String getability()...
Could you double check my program? I cannot get it to run. If you could tell...
Could you double check my program? I cannot get it to run. If you could tell me any changes that need to be made as well show the output I would greatly appreciate it. LinkedList.java public class LinkedList { class Node{ int value; Node nextElement; public Node(int value) { this.value = value; this.nextElement = null; } } public Node first = null; public Node last = null; public void addNewNode(int element) { Node newValueNode = new Node(element); if(first == null)...
Python programming: can someone please fix my code to get it to work correctly? The program...
Python programming: can someone please fix my code to get it to work correctly? The program should print "car already started" if you try to start the car twice. And, should print "Car is already stopped" if you try to stop the car twice. Please add comments to explain why my code isn't working. Thanks! # Program goals: # To simulate a car game. Focus is to build the engine for this game. # When we run the program, it...
Part four: using JDBC with mysql for project management program. I cannot copy the whole code,...
Part four: using JDBC with mysql for project management program. I cannot copy the whole code, so will split it into a few parts. See part one and two and three. Part four of The code is (starts at line 499, rest of code): } } catch (Exception e) { e.printStackTrace(); } if (foundSomething) { // pass } else { System.out.print("Search result is empty!\n"); } goBacktoMenu(); // go back to main menu } static void finalizeMenu(ArrayList<ProjectDetails> projectList) { System.out.print("========================Finalize project==========================\n\n");...
The source code I have is what i'm trying to fix for the assignment at the...
The source code I have is what i'm trying to fix for the assignment at the bottom. Source Code: #include <iostream> #include <cstdlib> #include <ctime> #include <iomanip> using namespace std; const int NUM_ROWS = 10; const int NUM_COLS = 10; // Setting values in a 10 by 10 array of random integers (1 - 100) // Pre: twoDArray has been declared with row and column size of NUM_COLS // Must have constant integer NUM_COLS declared // rowSize must be less...
In C++ fill in the comments the easiest to get the program work and get this...
In C++ fill in the comments the easiest to get the program work and get this output. Sample Output Please input the x: 2.5 Please input the y: -5 Please input the x: 3 Please input the y: 7.5 You entered: ( 2.5, -5 ) and ( 3, 7.5 ) point3 is ( 2.5, -5 ) Press any key to continue . . . #include <iostream>   // For cout and cin #include <iomanip>    // For formatting output, e.g. setprecision #include...
I have the following python code. I get the following message when running it using a...
I have the following python code. I get the following message when running it using a test script which I cannot send here: while textstring[iterator].isspace(): # loop until we get other than space character IndexError: string index out of range. Please find out why and correct the code. def createWords(textstrings): createdWords = [] # empty list for textstring in textstrings: # iterate through each string in trxtstrings iterator = 0 begin = iterator # new begin variable while (iterator <...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT