In: Computer Science
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);
}
}
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);
}
}
}