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...
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 am struggling with this assignment. I can't get the program to run when I enter...
I am struggling with this assignment. I can't get the program to run when I enter a number with the $ symbol followed by a number below 10. any help would be greatly appreciated. Create a program named Auction that allows a user to enter an amount bid on an online auction item. Include three overloaded methods that accept an int, double, or string bid. Each method should display the bid and indicate whether it is over the minimum acceptable...
I am trying to get this code to work but I am having difficulties, would like...
I am trying to get this code to work but I am having difficulties, would like to see if some one can solve it. I tried to start it but im not sure what im doing wrong. please explain if possible package edu.hfcc; /* * Create Java application that will create Fruit class and Bread class * * Fruit class will have 3 data fields name and quantity which you can change. * The third data field price should always...
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()...
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...
Hi I have a java code for my assignment and I have problem with one of...
Hi I have a java code for my assignment and I have problem with one of my methods(slice).the error is Exception in thread "main" java.lang.StackOverflowError Slice method spec: Method Name: slice Return Type: Tuple (with proper generics) Method Parameters: Start (inclusive) and stop (exclusive) indexes. Both of these parameters are "Integer" types (not "int" types). Like "get" above, indexes may be positive or negative. Indexes may be null. Description: Positive indexes work in the normal way Negative indexes are described...
I have three different homework questions I cannot seem to get My hw is due at...
I have three different homework questions I cannot seem to get My hw is due at 12 so if anyone can help that would be helpful Thank you 1)   For a car moving with speed v, the force of air drag is proportional to v2. If the power output of the car's engine is quadrupled, by what factor does the speed of the car increase? 2)Tarzan (m = 76 kg) commutes to work swinging from vine to vine. He leaves...
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…)
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT