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 need the c# code for the below assignment. Complete PigLatin program in Windows Forms GUI....
I need the c# code for the below assignment. Complete PigLatin program in Windows Forms GUI. Zip the solution project file and attach to this submission. Do this in the GUI format (Windows Form). Be sure and add a Clear Button to reset for entering another word or words. PigLatinGUI Basic Steps in Creating your Program Create your user interface (GUI). Use different font styles but don’t overdo it, Use colors, and Use graphics (You can find all kinds of...
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...
C# Tip Calculator. I can't figure the code out for this assignment can I get some...
C# Tip Calculator. I can't figure the code out for this assignment can I get some help For this assignment, you'll create a simple tip calculator. Expected program flow: Ask the user for the bill total. Ask the user for the tip percent. Print the final output in the following format when the user enters 10 and 15 for the first two prompts: Total for bill $10.00 with a 15% tip is $11.50 Note that the money values should be...
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()...
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...
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)...
I have been working on this assignment in Java programming and can not get it to...
I have been working on this assignment in Java programming and can not get it to work. This method attempts to DECODES an ENCODED string without the key.    public static void breakCodeCipher(String plainText){ char input[]plainText.toCharArray(); for(int j=0; j<25; j++){ for(int i=0; i<input.length; i++) if(input[i]>='a' && input[i]<='Z') input[i]=(char)('a'+((input[i]-'a')+25)%26); else if(input[i]>='A'&& input[i]<='Z') input[i]=(char)('A'+ ((input[i]-'A')+25)%26); } System.out.println(plainText)    }
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...
In Python I have a code: here's my problem, and below it is my code. Below...
In Python I have a code: here's my problem, and below it is my code. Below that is the error I received. Please assist. Complete the swapCaps() function to change all lowercase letters in string to uppercase letters and all uppercase letters to lowercase letters. Anything else remains the same. Examples: swapCaps( 'Hope you are all enjoying October' ) returns 'hOPE YOU ARE ALL ENJOYING oCTOBER' swapCaps( 'i hope my caps lock does not get stuck on' ) returns 'I...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT