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 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,...
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 already have the code of this program, I just want to know how to fix...
I already have the code of this program, I just want to know how to fix the code to Implement the 5th function (System.nanotime() and System.currentTimeMillis() methods) What Code does: Introduction Searching is a fundamental operation of computer applications and can be performed using either the inefficient linear search algorithm with a time complexity of O (n) or by using the more efficient binary search algorithm with a time complexity of O (log n). Task Requirements In this lab, you...
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 keep getting minor errors I can't figure out and I don't know how to convert...
I keep getting minor errors I can't figure out and I don't know how to convert decimal .10 to percentage 10% either.   With these functions defined now expand the program for a company who gives discounts on items bought in bulk. Create a main function and inside of it ask the user how many different items they are buying. For each item have the user input a price and quantity, validating them with the functions that you wrote. Use your...
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   ...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT