The basis of my problem is here: https://github.com/experiencethebridge1/primeGap
Bottom line, I want to create an array in which the output of a method will populate the elements of the new array.
This is not homework.
package primenumbermethod;
import java.util.Scanner;
public class PrimeNumberMethod {
public static void main(String[] args) {
System.out.print("How many prime numbers do you want to work with? ");
Scanner input = new Scanner(System.in);
int arraySize = input.nextInt();
// Invoke printPrimeNumbers method
System.out.println("If I can ever get it to work, the number of the "
+ "elements in the array I want to build will be " + arraySize +".");
System.out.println();
printPrimeNumbers(arraySize);
// How can I read parts of a method into elements of an array?
int[] myList = new int[arraySize];
}
public static int printPrimeNumbers(int numberOfPrimes) {
final int NUMBER_OF_PRIMES_PER_LINE = 10; // Display 10 per line
Scanner input = new Scanner(System.in);
System.out.print("What number do you want to start from? ");
int number = input.nextInt();
int count = 0; // Count the number of prime numbers
// Repeatedly find prime numbers
while (count < numberOfPrimes) {
// Print the prime number and increase the count
if (isPrime(number)) {
count++; // Increase the count
if (count % NUMBER_OF_PRIMES_PER_LINE == 0) {
// Print the number and advance to the new line
System.out.printf("%-15d\n", number);
} else {
System.out.printf("%-15d", number);
}
}
number++;
}
return 0;
}
// Method for checking if number is prime
public static boolean isPrime(int number) {
for (int divisor = 2; divisor <= number / 2; divisor++) {
if (number % divisor == 0) {// If true, number is not prime
return false; // Number is not a prime
}
}
return true; // Number is prime
}
}
Tried using global variables, abstraction does not apply (but could).
The main method initiates the program, then traces to method printPrimeNumbers, then into method boolean isPrime. I want to return the output of that method into a new array...
The array size will be defined by the user input <"How many prime numbers do you want to work with? ">, and then <"What number do you want to start with?>
Problem, I can't seem to pass the output of a method into the elements of an array.
Thoughts?
I would suggest you should restructure your code in the following way:
public static void main(String[] args) {
int numberOfPrimes = readIntFromCommandLine...;
int numberToStartWith = readIntFromCommandLine...;
int[] primeNumbers = getPrimeNumbers(numberOfPrimes, numberToStartWith);
// maybe extract this to another method as well
for (int prime : primeNumbers) {
// do whatever you want with prime, e.g. print it - or sum it, or multiply or whatever
}
}
public static int[] getPrimeNumbers(int amount, int from) {
int[] primes = new int[amount];
int count = 0;
/* now put your current prime logic here and whenever you
find a prime set primes[count] = newlyFoundPrime; */
}
public static boolean isPrime(int number) { /* stays the same */ }
It is generally a good idea to only ask for user input at a well defined point in your code, not all over the place. Therefore I placed the two inputs at the front. Another generally good idea is to make every method (maybe except for the main method) only do one thing. Your isPrime is a good example of that. Moving the printing logic out of getPrimeNumbers simplifies that method and lets you handle the printing at another, dedicated place.
Related
After writing 1 on scanner I want a random dice number generated and after pressing 1 again I want another random number generated but now I want it added with previous number. I want to make a loop, I want to keep pressing 1 and keep adding random numbers till I reach a certain number.
Thank you.
import java.util.Random;
import java.util.Scanner;
public class dice {
public static void main(String[] args) {
// TODO Auto-generated method stub
for (int k = 0; k < 100; k++) {
Scanner scan = new Scanner(System.in);
int s = scan.nextInt();
System.out.println(s);
int previous = s;
if (s == 1) {
Random ran = new Random();
int n = ran.nextInt(6) + 1;
System.out.print(n);
int next;
while (true) {
next = scan.nextInt();
if (next == 1) {
System.out.println(previous);
}
previous = n + 10;
}
}
}
}
}
Define previous outside the for loop, and replace
int previous = s;
previous = n + 10;
with
previous += s;
previous += n + 10;
Scanner sc=new Scanner(System.in);
int sum=0;
for(;;)
{
if(sc.nextInt()==1)
{
int num = (int)(Math.random()*6); // using the pre-defined random function in java.lang.Math class
System.out.println("Dice Value: "+num);
sum+=num; // shorthand adding the number for each iteration
}
//if(sum>100)
// break;
//if statement to check if value of sum is greater/lesser than a specific number
}
System.out.println("Final Answer: "+sum)
Something like this might work (not yet tested): an infinite loop that can be terminated as per choice.
If you are looking for a way that the program works as soon as you physically press the '1' key on your keyboard, without having to press the enter key, something like a keyevent might work:
https://docs.oracle.com/javase/7/docs/api/java/awt/event/KeyEvent.html
Please do let me know if there are any errors or doubts :)
My class has just started learning how to write code in a format with functions and methods, and this is my first attempt at it - I feel like I'm just confusing myself.
The assignment is to create a pool of numbers 1 to a randomly selected number and to store the pool in an array; then print the pool; then a user selects a number from the pool, and the program finds the divisors of that number and stores them in another array that will then be printed.
I am having problems with getting the divisors, storing them in a new array and then printing the array.
import java.util.Scanner;
import java.util.Random;
public class GetDivisors {
public static void main (String[] args){
Scanner read = new Scanner(System.in);
int []pool = new int[100];
int []divisors = new int[100];
int size;
int pick;
int numDivisor;
// Program Heading
printProgramHeading();
// Input and test
size = createPool(pool);
printPool(pool, size);
System.out.println();
System.out.println();
System.out.println("Enter a non-prime value listed in the pool above: ");
pick=read.nextInt();
// Data Processing
numDivisor = getDivisors(pool, divisors, pick);
// Output Section
printDivisors(divisors, size, pick);
} // end main
// Function and Method Specifications
// Name : printProgramHeading
// Description : This method prints the program heading to the monitor in all caps and with a dividing line
// : followed by a blank line.
// Parameters : None.
// Return : None.
public static void printProgramHeading() {
System.out.println("\tGET DIVISORS");
System.out.println(" ************************");
System.out.println();
} // end printHeading
//Name : createPool
//Description : This funtion generates an array of consecutive integers from 1 to a randomly generated
// : number no greater than 100.
//Parameters : An integer array.
//Return : An integer (the randomly generated number), representing the size of the array.
public static int createPool(int[]pool) {
Scanner read = new Scanner(System.in);
Random random = new Random();
int size=0;
size=random.nextInt(100)+1;
pool=new int[size];
return(size);
} // end createPool
//Name : printPool
//Description : This method prints the pool of numbers to the monitor no more than 10 per line.
//Parameters : The pool array, and the size of the pool in that order.
//Return : None.
public static void printPool(int[] pool, int size) {
int index;
int count=0;
for(index=1; index<size; index++){
System.out.print(pool[index]=index);
System.out.print(" ");
count++;
if(count == 10){
System.out.println();
count=0;
} // end if loop
} // end for loop
} // end printPool
//Name : getDivisors
//Description : This funtion stores all the divisors of the user's pick into the divisor array.
//Parameters : The pool array, the divisor array, and the user's pic, in that order.
//Return : The number of divisors found.
public static int getDivisors(int[] pool, int[] divisors, int pick){
int numDivisors = 0;
int index = 0;
for(index=1; index <= pick; index++){
if(pick % index == 0){
numDivisors++;
divisors[index] = index;
} // end if loop
} // end for loop
return(numDivisors);
} // end getDivisors
//Name : printDivisors
//Description : This method prints the contents of the divisors array to the monitor all on one line with
// : a leading label.
//Parameters : The divisor array, an integer representing the number of divisors. and the user's pick
// : in that order.
//Return : None.
public static void printDivisors(int[] divisors, int size, int pick){
int index = 0;
System.out.println("The divisors of " + pick + ": " + divisors[index] + " ");
} // end printDivisors
} // end class
Thank you!
This is obviously a school project. In order for you to learn I don't want to give you the answers but i'll point out your mistakes, so that you can fix your problems.
First in this method createPool:
//Name : createPool
//Description : This funtion generates an array of consecutive integers from 1 to a randomly generated
// : number no greater than 100.
//Parameters : An integer array.
//Return : An integer (the randomly generated number), representing the size of the array.
public static int createPool(int[]pool) {
Scanner read = new Scanner(System.in);
Random random = new Random();
int size=0;
size=random.nextInt(100)+1;
pool=new int[size];
return(size);
} // end createPool
Look closer at the values that are stored in the array.
Second in method printPool:
//Name : printPool
//Description : This method prints the pool of numbers to the monitor no more than 10 per line.
//Parameters : The pool array, and the size of the pool in that order.
//Return : None.
public static void printPool(int[] pool, int size) {
int index;
int count=0;
for(index=1; index<size; index++){
System.out.print(pool[index]=index);
System.out.print(" ");
count++;
if(count == 10){
System.out.println();
count=0;
} // end if loop
} // end for loop
} // end printPool
You are updating the values of the pool. This method should only print the values in the pool. You should be setting the values of the pool in createPool, and printing the values of the pool in printPool.
Next in the getDivisors method
//Name : getDivisors
//Description : This funtion stores all the divisors of the user's pick into the divisor array.
//Parameters : The pool array, the divisor array, and the user's pic, in that order.
//Return : The number of divisors found.
public static int getDivisors(int[] pool, int[] divisors, int pick){
int num = 0;
int divisor = 0;
int numDivisors = 0;
int index = 0;
for(pool[index]=1; pool[index]<=pick; pool[index]){
num = pick % pool[index];
if(num == 0){
divisor = num;
numDivisors++;
divisors= new int[divisor];
} // end if loop
} // end for loop
return(numDivisors);
} // end getDivisors
You have a lot of things wrong with this method. First, re-look at your for loop. I really think you need to learn further about how for loop should operate and when is the best time for use for loops. Your underlying understanding of for loops in flawed. Your logic is right for calculating the divisor, but you have two issues related to this logic. 1) Relook at how you put the new divisor into the divisors array. This is related to the earlier issue of how you use the for loop. Once you solve the for loop problem, this should become more clear 2) What should you store into the divisors array when num == 0 is false? You need to handle this case, right?
Now onto the printDivisors method:
//Name : printDivisors
//Description : This method prints the contents of the divisors array to the monitor all on one line with
// : a leading label.
//Parameters : The divisor array, an integer representing the number of divisors. and the user's pick
// : in that order.
//Return : None.
public static void printDivisors(int[] divisors, int size, int pick){
int index = 0;
System.out.println("The divisors of " + pick + ": " + divisors[index] + " ");
} // end printDivisors
Once again, you really need to understand when and when-not to use a for loop. This method should print out all the values in the divisors array. Currently, this method only prints out one value in the divisors array (the first value, at index 0).
Finally, in the main() function:
public static void main (String[] args){
Scanner read = new Scanner(System.in);
int []pool = new int[100];
int []divisors = new int[100];
int size;
int pick;
int divisor;
// Program Heading
printProgramHeading();
// Input and test
size = createPool(pool);
printPool(pool, size);
System.out.println();
System.out.println();
System.out.println("Enter a non-prime value listed in the pool above: ");
pick=read.nextInt();
// Data Processing
divisor = getDivisors(pool, divisors, pick);
// Output Section
printDivisors(divisors, size, pick);
} // end main
Should int[] pool, and int[] divisors be initialized initially with an arbitrary size of 100? Random numbers like these are usually called "magic numbers". Magic numbers should either be set as a constant with a description, or taken out of the program. Next, you print the header. This seems ok. Then you create the pool, and save the pool size into size, and print the pool with the given size passed into the function. This all seems fine. Next you poll the user for a divisor input, and call the getDivisors function with the user input. Also you save the output into a variable divisor, which represent the size of the divisor array. Now, look at the parameters you pass into printDivisors, something smells fishy here...
These are all of the issues that I see with your code. This should give you plenty of information on how to improve your mistakes. If you have anymore questions please feel free to ask.
Sorry I can't comment your question. Is it ok if you use Collections instead of arrays?
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class GetDivisorsRefactored {
private static Integer[] pool;
private static Scanner read;
public static void main(String[] args) {
// Program Heading
printProgramHeading();
initPool();
System.out.println("Available list: ");
printArray(pool);
read = new Scanner(System.in);
System.out.println();
System.out.println();
System.out.println("Enter a non-prime value listed in the pool above: ");
int pick=read.nextInt();
Integer[] divisors = findDivisors(pick);;
printArray(divisors);
}
private static void printArray(Integer[] someArray) {
int nextRow = 0;
for (int num: someArray){
System.out.printf("%4d,", num);
if (++nextRow > 9){
System.out.println();
nextRow =0;
}
}
}
private static Integer[] findDivisors(int pick) {
List<Integer> divisors = new ArrayList<Integer>();
for (int index = 1; index < pool.length; index++){
if ((pick % pool[index]) == 0){
divisors.add(pool[index]);
}
}
return divisors.toArray(new Integer[divisors.size()]);
}
private static void initPool() {
int size = (int) (Math.random()*100) + 1;
pool = new Integer[size];
for (int index = 0; index < pool.length; index++){
pool[index] = index;
}
}
// Function and Method Specifications
// Name : printProgramHeading
// Description : This method prints the program heading to the monitor in
// all caps and with a dividing line
// : followed by a blank line.
// Parameters : None.
// Return : None.
public static void printProgramHeading() {
System.out.println("\tGET DIVISORS");
System.out.println(" ************************");
System.out.println();
} // end printHeading
}
I am have a program which prints off the fibonacci sequence up to a given input. The user puts in a number and it prints out the sequence up to that many numbers.
ex: input = 4 prints 1 1 2 3
I want to limit the program to only allowing an input 1-16. The way I have it now will print the sequence an then prints the error message? Any suggestions? Thank you
public class FibonacciGenerator
{
private int fibonacci = 1;
public FibonacciGenerator()
{
}
public int Fibonacci(int number)
{
if(number == 1 || number == 2)
{
return 1;
}
else if (number > 16)
{
System.out.println("Error must select 1-16");
}
else
{
int fib1=1, fib2=1;
for(int count= 3; count < 17 && count <= number; count++)
{
fibonacci = fib1 + fib2;
fib1 = fib2;
fib2 = fibonacci;
}
}
return fibonacci;
}
}
Here is my main method:
import java.util.Scanner;
public class FibonacciPrinter
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
System.out.print("Enter an integer 1-16: ");
int input = in.nextInt();
FibonacciGenerator newNumber = new FibonacciGenerator();
System.out.println("Fibonacci sequence up to " + input + " places.");
for(int fibCount = 1; fibCount <= input; fibCount++)
{
int sequence = newNumber.Fibonacci(fibCount);
System.out.print(sequence);
}
}
}
As a recommendation don't make your methods or variables start with capital letter, capital letter is used by convention for Classes only.
Also, you should validate input variable before passing it to your method.
I mean:
if (input > 16 || input < 1) {
System.out.println("Enter a number between 1-16");
}
else {
for(int fibCount = 1; fibCount <= input; fibCount++)
{
int sequence = newNumber.Fibonacci(fibCount);
System.out.print(sequence);
}
}
In your Fibonacci function, your first line should be an if statement to see if the number is greater than 16. If it is, then you can throw an error.
Below is what it should be:
public int Fibonacci(int number) {
if (number > 16 || number < 1) throw new IllegalArgumentException("Error. Must select 1-16.");
// Rest of the code
}
In your Fibonacci function, for number not equal to 1 and 2. The return statement return fibonacci; will always be called. That's why the error message is printed with the sequence.
To avoid this, you can use #Frakcool method to validate variable input before passing it to Fibonacci function. Alternatively, you may use do-while loop to do this (force the user to retry).
do{
System.out.print("Enter an integer 1-16: ");
input = in.nextInt();
if (input<1 || input>16)
System.out.println("Error. Must select within 1-16.");
}while(input<1 || input>FibonacciGenerator.upper_limit);
Some other suggestion:
Make your methods and variables name start with a lower case letter
To avoid repeat calculation (for-loop in Fibonacci method), use integer array to store the fibonacci values and pass integer array instead of integer (for small input number such as 16). Another way is to set two more global variables to store the last and second last calculated values.
Make upper limit (and/or lower limit) as a global variable for better maintenance
public static int upper_limit = 16;
and get it in other class as
FibonacciGenerator.upper_limit
Please see my comments in the code to better explain things. Basically having issues with the methods below. I can get the load method to run but I am unsure whether the numbers entered by the user are actually being stored in the array.
In addition, the search method has been throwing things off and i think its going in a loop.
See below for more. Thank you in advance.
import java.util.Scanner;
public class MyContainer {
private int[] values;
private int size;
public MyContainer(){
values=new int[50];
size=0;}
//Load Method - Display a message to the user
//and get positive intergers from user
public void load()
{
int input;
Scanner in = new Scanner(System.in);
System.out.println("Enter a series of positive integers (Negative to Terminate): ");
input=in.nextInt();
while (input >=0) {
values[size]=input;
size++;
input=in.nextInt();
}
}//End Load
//Compute Average from the above entered numbers
public double computeAverage() {
double avg= 0.0;
int count = 0;
while(values[size] >=0)
{avg = avg + values[size];
count++;
}
size = size + 1;
avg = avg / size;
return avg;
}
//Get user input to search for a number in the array
public boolean search(int myInt){
while(values[size] >=0) {
if (values[size] == myInt){
return true;}
else{
size++;}
}
return false;
}
//print the position of the number
public void print(){
for(int i=0;i>=size;i++) {
System.out.println("The number at position " + i + " is " + values[i]);
}
}
}
That is what I have so far. I also have created a tester class for the above container.
class Tester {
public static void main(String[] args) {
MyContainer in = new MyContainer();
in.load();
in.computeAverage();
in.search(); //i know for a fact this is wrong just stuck
in.print();
}
}
Any advise/help would be greatly appreciated. My professor is terrible at teaching and the book only partially explains things.
Your search() method has parameters that you aren't passing.
you declare it as...
public boolean search(int myInt) {
while (values[size] >= 0) {
if (values[size] == myInt) {
return true;
} else {
size++;
}
}
return false;
}
but call it with...
in.search();
This code won't even compile. For argument sake I set this to 5.
In your computeAverage() method, this is an infinite loop...
while (values[size] >= 0) {
avg = avg + values[size];
count++;
}
The main problem I believe you are running into is the reuse of your size variable. In the load function it will work as expected say for loading in 10 numbers size will be 10 and elements 0->9 in values will have numbers in them. However when you get to computeAverage size will still be 10. So you are in an infinite loop.
while(values[size] >= 0) {
avg = avg + values[size];
count++;
}
First iteration you will check values[10] (which is wrong remember valid elements are only in 0->9 if size is 10). Next iteration avg and count are increased but size remains the same so you will add the same number to avg and continue in the loop. You should use a different conditional for your while loops in computeAverage and search. The last negative number entered to quit will not be in the array; you will need to use something else. As a hint it will involve count and size.
FYI: I am a beginner. Also, I understand that calling methods is a novice concept and there are a few threads like this already. My situation is a little different because I am very restricted by pseudo-code that my program must mirror identically. I am having trouble calling methods from other methods, including calling a method from inside main. Here is the pseudo-code followed by the code that I wrote:
PSEUDO-CODE:
// The user enters an integer and the program calculates that many primes
// It uses 3 methods, including the main. All the methods are in the same class
// and should be declared as ‘public static.’
Project Print the First n Primes
Package printTheFirstNPrimesPackage
Class PrintTheFirstNPrimes
Method Main
Declare numberOfPrimes as integer
Print “How many prime numbers do you want?"
Read numberOfPrimes from the keyboard
Call the method: PrintNPrimes(numberOfPrimes)
end Method (Main)
// ***********************************************************
// This method accepts an integer and prints that many prime
// numbers, starting at 2. 2 is the lowest primt number.
// ***********************************************************
Method void PrintNPrimes(int n)
declare i as integer
declare myNum as integer
myNum = 2 // The first prime number
i = 0
loop while i < n // This could be a ‘for’ loop
if IsPrime(myNum) // Call the Isprime method, (see below)
i = i + 1
print myNum
End If
myNum = myNum + 1
end loop
end Method PrintNPrimes
// **********************************************************
// This method accepts an integer and tests to see if it is
// a prime number. If it is prime, the method returns true,
// otherwise it returns false.
// **********************************************************
Method boolean IsPrime(int number)
Declare result as boolean
result = true
declare i as integer
i = 2
loop while i < number
if ((number % i) == 0)
result = false
exit loop
end if
end loop
return result
end Method
end Class
End Package
End Project
JAVA CODE:
package printTheFirstNPrimesPackage;
import java.util.*;
public class PrintTheFirstNPrimes {
public static void main(String [] args) {
int numberOfPrimes;
Scanner primes = new Scanner(System.in);
System.out.println("How many prime numbers do you want?");
numberOfPrimes = primes.nextInt();
// Call the method PrintNPrimes(numberOfPrimes)
}
public static void PrintNPrimes(int n) {
int i;
int myNum;
myNum = 2; // The first prime number
i = 0; {
while (i < n)
// if IsPrime(myNum) // Call the IsPrime method (see below) {
i = i + 1;
System.out.println(myNum);
myNum = myNum + 1;
}
}
public static boolean IsPrime(int number) {
boolean result;
result = true;
int i = 2;
while (i < number) {
if ((number % 1) == 0)
result = false;
}
return result;
}
}
My main issue is calling the IsPrime method within the if statement. I get an error saying the IsPrime cannot be converted from int to boolean which I knew, but the pseudo-code restricts me from doing much else. I also would like advice on how I should call the PrintNPrimes method within method main. Thanks.
Because your PrintNPrimes is static method, you can just call the method by passing the numberofPrimes.
Example:
public static void main(String [] args) {
int numberOfPrimes;
Scanner primes = new Scanner(System.in);
System.out.println("How many prime numbers do you want?");
numberOfPrimes = primes.nextInt();
PrintNPrimes(numberOfPrimes);
}
..........
Note: Java naming convention suggests that use first letter as small case letter while defining methods.
You can follow same approach to invoke other methods.
if IsPrime(myNum)
needs to be
if (IsPrime(myNum))
Also be sure to restore your curly braces. I don't see any reason why this will cause an error. Please post the exact error message if you still have problems.
Update code below with resolution for both (including if statement) of your compilation errors:
printNPrimes(numberOfPrimes);
if (isPrime(myNum)) // Call the IsPrime method (see below) {
Full updated code:
public static void main(String [] args) {
int numberOfPrimes;
Scanner primes = new Scanner(System.in);
System.out.println("How many prime numbers do you want?");
numberOfPrimes = primes.nextInt();
printNPrimes(numberOfPrimes);
}
public static void printNPrimes(int n) {
int i;
int myNum;
myNum = 2; // The first prime number
i = 0; {
while (i < n)
if (isPrime(myNum)) // Call the IsPrime method (see below) {
i = i + 1;
System.out.println(myNum);
myNum = myNum + 1;
}
}
public static boolean isPrime(int number) {
boolean result;
result = true;
int i = 2;
while (i < number) {
if ((number % 1) == 0)
result = false;
}
return result;
}
I didn't check the logic.