Question

In: Computer Science

I'm getting an error message with this code and I don't know how to fix it...

I'm getting an error message with this code and I don't know how to fix it

The ones highlighted give me error message both having to deal Scanner input string being converted to an int. I tried changing the input variable to inputText because the user will input a number and not a character or any words. So what can I do to deal with this

import java.util.Scanner;
public class Project4 {

/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// Find Prime Numbers using sequential divisors.
String inputText;
int numberOfPrimes;
  
Scanner input = new Scanner(System.in);
System.out.printf("How many primes to calculate? ");
inputText = input.nextLine();
numberOfPrimes = Integer.parseInt(inputText);
  
int[] primes = new int[input];
int primeCount = 0;
int divisorsCount = 0;
int number = 2;
double sqrt;
boolean isPrime;
  
while(primeCount < input) {
isPrime = false;
sqrt = Math.sqrt(number);
for(int i = 0; i < primeCount; i++) {
if(primes[i] <= sqrt) {
divisorsCount++;
if(number % primes[i] == 0) {
isPrime = false;
}
  
}
}
}
if(isPrime) {
primes[primeCount] = number;
primeCount++;
divisorsCount=0;
System.out.println("prime = " + primeCount + "count = " + number
+ ", " + "divisorsCount = " + divisorsCount);
}
  


}

Solutions

Expert Solution

Here Scanner is object which is used to get the input from the user.You should use input value directly for n.This input should be used to to read values like int,float,string etc.like input.nextInt() for Int,Input.nextFloat() for float,input.nextLine() for a sentence.

I don't know what program it is but it will go to infinite loop if you execute it because you are not changing isprime value anywhere to true and also you are not incrementing primeCount value because of that while condition will go to infinite loop.

import java.util.*;
public class Main{

/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// Find Prime Numbers using sequential divisors.
String inputText;
int numberOfPrimes;
  
Scanner input = new Scanner(System.in);
System.out.printf("How many primes to calculate? ");
//you can directly take the values as int n=input.nextInt()
inputText = input.nextLine();

numberOfPrimes = Integer.parseInt(inputText);
int[] primes = new int[numberOfPrimes];
int primeCount = 0;
int divisorsCount = 0;
int number = 2;
double sqrt;
boolean isPrime=false;
while(primeCount < numberOfPrimes) {
isPrime = false;
sqrt = Math.sqrt(number);
for(int i = 0; i < primeCount; i++) {
if(primes[i] <= sqrt) {
divisorsCount++;
if(number % primes[i] == 0) {
isPrime = false;
}
  
}
}
}
if(isPrime) {
primes[primeCount] = number;
primeCount++;
divisorsCount=0;
System.out.println("prime = " + primeCount + "count = " + number+ ", " + "divisorsCount = " + divisorsCount);
}
}
}


Related Solutions

I'm Getting an "unindented error" Please fix the bolded codes. Because I don't know whats going...
I'm Getting an "unindented error" Please fix the bolded codes. Because I don't know whats going on. Thank You. # This program exercises lists. # The following files must be in the same folder: # abstractcollection.py # abstractlist.py # arraylist.py # arrays.py # linkedlist.py # node.py # input.txt - the input text file. # Input: input.txt # This file must be in the same folder. # To keep things simple: # This file contains no punctuation. # This file contains...
Hello I have this error in the code, I do not know how to fix it....
Hello I have this error in the code, I do not know how to fix it. It is written in C++ using a Eclipse IDE Error: libc++abi.dylib: terminating with uncaught exception of type std::out_of_range: basic_string bus.h =========== #pragma once #include using namespace std; class Bus { private:    string BusId; // bus ID    string Manufacturer; // manufacturer of the bus    int BusCapacity; // bus capacity    int Mileage; // mileage of bus    char Status; // current status...
I'm getting an error with my code on my EvenDemo class. I am supposed to have...
I'm getting an error with my code on my EvenDemo class. I am supposed to have two classes, Event and Event Demo. Below is my code.  What is a better way for me to write this? //******************************************************** // Event Class code //******************************************************** package java1; import java.util.Scanner; public class Event {    public final static double lowerPricePerGuest = 32.00;    public final static double higherPricePerGuest = 35.00;    public final static int cutOffValue = 50;    public boolean largeEvent;    private String...
I am getting an error at linen 57 and can't figure out how to fix it....
I am getting an error at linen 57 and can't figure out how to fix it. // Java program to read a CSV file and display the min, max, and average of numbers in it. import java.io.File; import java.io.FileNotFoundException; import java.util.Arrays; import java.util.Scanner; public class Main {     // method to determine and return the minimum number from the array     public static int minimum(int numbers[])     {         int minIdx = 0;         for(int i=1;i<numbers.length;i++)         {             if((minIdx...
I don't know why I keep getting the following error: AttributeError: 'tuple' object has no attribute...
I don't know why I keep getting the following error: AttributeError: 'tuple' object has no attribute 'size' I am using python in Anaconda. import numpy as np def information_gain(x_array, y_array): parent_entropy = entropy(x_array) split_dict = split(y_array) for val in split_dict.values(): freq = val.size / x_array.size child_entropy = entropy([x_array[i] for i in val]) parent_entropy -= child_entropy* freq return parent_entropy x = np.array([0, 1, 0, 1, 0, 1]) y = np.array([0, 1, 0, 1, 1, 1]) print(round(information_gain(x, y), 4)) x = np.array([0,...
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...
can someone tell me why I'm getting the error code on Eclipse IDE: Error: Main method...
can someone tell me why I'm getting the error code on Eclipse IDE: Error: Main method is not static in class StaticInitializationBlock, please define the main method as:    public static void main(String[] args) This is what I'm working on class A { static int i; static { System.out.println(1); i = 100; } } public class StaticInitializationBlock { static { System.out.println(2); } public static void main(String[] args) { System.out.println(3); System.out.println(A.i); } }
I'm getting an error for this code? it won't compile import java.util.*; import java.io.*; public class...
I'm getting an error for this code? it won't compile import java.util.*; import java.io.*; public class Qup3 implements xxxxxlist {// implements interface    // xxxxxlnk class variables    // head is a pointer to beginning of rlinked list    private node head;    // no. of elements in the list    // private int count; // xxxxxlnk class constructor    Qup3() {        head = null;        count = 0;    } // end Dersop3 class constructor   ...
Hey, I'm stuck on this assignment for AP Comp Sci Java. I don't know how to...
Hey, I'm stuck on this assignment for AP Comp Sci Java. I don't know how to start. An array of String objects, words, has been properly declared and initialized. Each element of words contains a String consisting of lowercase letters (a–z). Write a code segment that uses an enhanced for loop to print all elements of words that end with "ing". As an example, if words contains {"ten", "fading", "post", "card", "thunder", "hinge", "trailing", "batting"}, then the following output should...
It shows me that 1 error exists in this code but I didn't know how to...
It shows me that 1 error exists in this code but I didn't know how to fix this error so if you can help I will appreciate it. Language C++. Code: #include <iostream> #include <string> #include <iterator> #include <fstream> #include <sstream> #include <cstdlib> #include <set> using namespace std; class Book { private: string BookId; string BookISBN; string Publisher; int PublisherYear; double Price; int Quantity; string Author; public: string SetBookId(); string SetBookISBN(); string SetPublisher(); int SetPublisherYear(); double SetPrice(); int SetQuantity(); string...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT