Java: calling a method in method main - java

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.

Related

How does recursion work and how can recursion be used to manipulate integer digits?

I'm trying to learn java, and I can't seem to understand recursion. I can understand how recursion can be used to add and do other basic math operations but how can recursion be used to reverse manipulate integers and individual integer digits.
example:
a method takes a single positive integer argument and displays its base five equivalent. 231 returns 1411 but the code below returns 1141. how would I reverse the order of integers put out?
public void base5(int n){
int rem=n%5;
int vis=n/5;
if(n!=0){
// System.out.print(rem/*+"|"*/);
//
// rem=(rem+rem)*10;
// System.out.print("\n||"+n+"||\n");
System.out.print(rem);
base5(vis);
}
else{
return;
}
}
The algorithm for getting individual digits of an integer, from right to left, is well known. See How to get the separate digits of an int number?.
I won't "explain" recursion, but I'll give you one possible solution for first problem:
a method takes a single positive integer and displays it with commas
inserted every three digits
import java.util.Scanner;
class Main {
public static void main( String [] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter your positive integer: ");
long number = sc.nextLong();
String result = addCommas(number);
System.out.println(result);
}
public static String addCommas(long num) {
return addCommas(num, 1);
}
public static String addCommas(long num, int counter) {
if (num == 0) {
return ""; // base case ends recursion
}
else {
long digit = num % 10;
num = num / 10;
String comma = (counter%3==0 && num>0) ? "," : "";
// recursive call below because we call addCommas() again
return addCommas(num, counter+1) + comma + digit;
}
}
}
Here's a compact solution to the second problem:
a method takes a single positive integer and displays the result of
reversing its digits
public static String reverseDigits(long num) {
if (num == 0) {
return "";
}
else {
return String.valueOf(num % 10) + reverseDigits(num / 10);
}
}

Fibonacci sequence will not print anything but the number that is inputted by the user

Here is my main method, I am trying to call the Fibonacci sequence to tell me what number would be at the location the user inputs:
import java.util.Scanner; //import Scanner
public class Main {
public static void main(String[] args) {
System.out.println("enter number");
Scanner input = new Scanner(System.in);
int n = input.nextInt();
Fibonacci fibonacci_test = new Fibonacci();
fibonacci_test.Recursivefibonacci(n);
}
}
Here is my Fibonacci code that I have:
public class Fibonacci {
//Fn=F(n-1)+F(n-2)
//The recursive Fibonacci method
public int Recursivefibonacci(int n) {
if(n==0) {
return 0;
} if(n==1) {
return 1;
}else {
int fib = Recursivefibonacci(n-1)+Recursivefibonacci(n-2);
return fib;
}
}
}
I cannot get this thing to print anything. How can I fix this?
It's because you're not printing anything else.
Your method doesn't print anything (just returns a value), and your main doesn't print anything (aside from "enter number").
You can try changing: fibonacci_test.Recursivefibonacci(n); to println (fibonacci_test.Recursivefibonacci(n));
It would be more appropriate to return Recursivefibonacci(n-1)+Recursivefibonacci(n-2);rather than storing it in a variable.
I did this in python, you can have a look, try to adapt it to java, this might help you. Recursivity can be a headache but seems good.
def fib(n):
if n == 0:
return 0
if n <= 1:
return 1
res = (fib(n-1)+ fib(n-2))
return res
///////
Probably your code will look somehow like this:
public int Recursivefibonacci(int n) {
if(n == 0){
return 0;
}
if(n <= 1) {
return 1;
}
int fib = Recursivefibonacci(n-1)+Recursivefibonacci(n-2);
return fib;
}
Try it! and let me know if it worked.

How to pass method output into an array element?

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.

Java giving error :incomparable types: boolean and int" even though both methods are boolean?

What Im trying to code is that a user inputs a number n and the program outputs all the numbers from 1 to n that are both prime numbers and palindrome numbers.
I created a method for finding prime numbers and another for finding if a number is a palindrome. My code for outputting the integers that are both goes like
if ((prime(y)==true) && (pal(y)==n)) {
System.out.println(y);
}
Here is my method for finding prime numbers:
public static boolean prime(int n) {
int x = 2;
while (n%x>0) {
x+=1;
} if (x==n) {
return true;
} else {
return false;
}
}
Here's my method for finding palindrome numbers:
public static boolean pal(int n) {
int rev = 0;
int rmd = 0;
while (n>0) {
rmd = n%10;
rev = rev*10 + rmd;
n = n/10;
} if (rev==n) {
return true;
} else {
return false;
}
}
I get the error that these two methods are not comparable because apparently one is boolean and the other integer. Anyone know how to fix this?
Your statement says pal(y)==n, but pal(y) returns a boolean. I'm not sure what comparing it to n is supposed to do.
In general, avoid statements like foo == true. If it's already a boolean, just use foo, or for false !foo.

SumDigits using Parameter

Okay, so I created a DigitsSum application. The class is DigitsSum and it does contain a static method called sumDigits(I AM DONE WITH THIS). ( However I didn't get this part) The names must match these including the capitalization, the sumDigits method should take a single parameter, an integer, and return the sum of the digits in that integer, sumDigits method should not print anything, and it should return its answer using a return statement. I can use a main method to test my sumDigits method, and all printing should happen there. I would like to know whether if i did perfectly fine or no..also method return should be like if entered a number, suppose 345, then output should be 3+4+5=12 --> 1+2 = 3. what i am doing wrong here? Thanks in advanced!
import java.util.Scanner;
public class SumDigits {
public static double sumDigits (int a){
int sum;
int t= a%10;
sum= t+t;
a = a/10;
return (sum);
}
public static void main (String [] args){
double sumDigit;
int integer;
Scanner in = new Scanner(System.in);
System.out.print("Enter a positive integer: ");
integer = in.nextInt();
sumDigit = sumDigits(integer);
System.out.println ("The sum of the digit is:" +sumDigit);
}
}
I believe that you're missing a few things:
You should always close streams and any external resource in general. id est: closing your Scanner before leaving your main method
As it has been pointed out in the comments, you should use a recursive method to implement sumDigits, because it reflects the actual behavior you're trying to implement.
Your code could be like this:
public class Main {
public static int sumDigits(final int a) {
int sum = 0;
int b = a;
do {
sum += b % 10;
b = b / 10;
} while (b > 0);
if (sum >= 10) {
return sumDigits(sum);
}
return sum;
}
public static void main(final String[] args) {
double sumDigit;
int integer;
try (final Scanner in = new Scanner(System.in)) {
System.out.print("Enter a positive integer: ");
integer = in.nextInt();
sumDigit = sumDigits(integer);
System.out.println("The sum of the digit is: " + sumDigit);
}
}
}
What I did here in the recursive method can be decomposed in two parts:
You calculate the sum of all the digits of the given number (done by the do/while loop)
If that sum itself is greater or equals to 10, then we need to return the recursive application of sumDigits on that value... otherwise, just return sum.
Note that I didn't only change the sumDigits method but also the main one, so it closes the Scanner using the try-with-resource syntax.

Categories