Passing integer from one method to another - java

Trying to write a program with two methods. First one takes an integer and prints its divisors as well as the sum of its divisors, the second is a boolean function that returns if the given integer is equal to the sum of its divisors (a perfect number).
I have the first method done fine but I want to take the integer sum from it and use it in the second method, is this even possible? Iv spent about quite a while trying to research it with no success.
As usual any and all advice appreciated. Code so far is below.
import java.util.Scanner;
import java.io.*;
class arrayTest {
public static int sumFacs(int n) {
int sumDiv[] = new int[50];
int c = 0;
int sum=0;
if(n<0){
System.out.println("Sorry I dont do negatives!");
}
else {
for(int i=1; i<=n; i++){
int j = n%i;
if(j==0){
System.out.println( i + " is a divisor of " + n + "\n");
sumDiv[c] = i;
c++;
}
}
for (int i=0; i<sumDiv.length; i++){
sum += sumDiv[i];}
System.out.println("The sum of the divisors of " + n + " is: " + sum);
}
return sum;
}
public static boolean isPerfect(int n, int sum) {
boolean b = (n == sum);
if(b){
System.out.println( n + " is a perfect number.");
}
else {
System.out.println( n + " is not a perfect number.");
}
}
public static void main(String[] args){
Scanner scanner = new Scanner(System.in);
System.out.println("Please enter a positive integer.");
int n = scanner.nextInt();
sumFacs(n);
int sumDivisors = sumFacs(n);
System.out.println(isDivisors(sumFacs(n), n));
isPerfect(n, sum);
}
}

Your sumFacs returns an integer, so you can definitely use whatever it yields in your isPerfect method. As you are doing it now, you are passing the same number to the methods. To do what you want, you will need to do something like so:
int sumFacsResult = sumFacs(n); //Take whatever value sumFacs yields, store it in sumFacsResult
System.out.println(isPerfect(sumFacsResult, n); //Take the result of sumFacs and pass it to the isPerfect method
or shorthand:
System.out.println(isPerfect(sumFacs(n), n)); //It is usually recommended to use the other approach, for readability purposed.
And your isPerfect method should be something like so:
public static boolean isPerfect(int sum, int number)
{
return sum == number;
}

your sumFacs(int n) has a return type of int and you are returning sum but where you call that method you are not setting it to anything so what you want to do is:
int foo = sumFacs(n);
isPerfect(n,foo);
and make your isperfect class
public static void isPerfect(int n, int foo)
{
if((n==foo)
{
System.out.println( n + " is a perfect number.");
}else{
System.out.println( n + " is not a perfect number.");
}
}
However this would all be easier in one class not two

Related

I am trying to write a recursive function that will return the result of the sum (integer) and takes one argument

I am trying to follow these instructions:
Write a program that will ask the user for the value of an integer n, and compute the sum 1 + 2 + 3 + 4 + ... + n. The requirement for this lab is that you write a recursive function that returns the result of the sum (integer) and takes one argument, n, of type integer. You will then call the function and print out its results as follows:
int mysum = recursive_addition(n);
System.out.println("The sum 1+2+...+n is: "+ mysum);
the problem is on line 20 because of the error below
Main.java:20: error: method main (String[]) Is already defined in class Main
private static void main (String args[])
^
Here is my code:
import java.util.Scanner;
public class Main {
public static void main(String[] args){
Scanner s = new Scanner(System.in);
System.out.print("Please enter a integer: ");
int n = s.nextInt();
int mysum = recurSum(n);
System.out.println("The sum 1+2+3+4 is :" + n );
}
public static int recurSum(int n)
{
if (n <= 0)
return n;
return n + recurSum(n - 1);
}
public static void main (String args[])
{
int n = 5;
System.out.println(recurSum(n));
}
}
As the compiler stated, you are duplicating the main entry points of your application.
Just remove the last main function and modify as follow
Here is the working code
import java.util.Scanner;
public class Main {
public static void main(String[] args){
Scanner s = new Scanner(System.in);
System.out.print("Please enter a integer: ");
int n = 5; // Just put there the number
int mysum = recurSum(n);
System.out.println("The sum 1+2+3+4 is :" + n );
}
public static int recurSum(int n)
{
if (n <= 0)
return n;
return n + recurSum(n - 1);
}
}

I am trying to write a program that allows me to input multiple integers, but it won't allow me to enter in my set of integers

My code won't allow me to enter in multiple integers to where it can then compute the sum, the count of integers, the minimum, and the sum of positive even integers. I am not sure if I need another method or if im calling for the wrong things.
import java.util.Scanner;
public class Assignment2 {
private static final Scanner input = null;
private static int n;
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
int sum=0, minNumber=0, nCount=0, countEvenIntegers=0;
Scanner sc = new Scanner(System.in);
int i = sc.nextInt();
//when code reads 0, code terminates
int[] numbers = new int[4];
for(int i=0; i<4; i++){
numbers[i] =sc.nextInt();
}
while(!(n==0)){
sum += n;
n = input.nextInt();
}
class SumOfValues {
public int sum(int...vals){
int sum=0;
for (int val : vals) {
sum+= val;
}
return sum;
}
}
class CountingInts{
public void main(String[] args){
Scanner input=new Scanner(System.in);
int count=0;
System.out.print("Numbers: ");
while (input.hasNextInt()){
input.nextInt();
count++;
}
System.out.print(count);
input.close();
}
}
int sumPositive = 0;
System.out.println("The minimum integer is " + minNumber + "\nThe count of integers is "
+ nCount + "\nThe sum of positive integers is " + sumPositive + "\nThe count of even integers in the sequence is " +
countEvenIntegers );
}
}
It looks like you are an absolute beginner, so I'd recommend not dealing with functions and classes and all that, and just write everything linearly. I'm not sure why you have all those functions, classes and variables, but to help you, this is probably the simplest way to achieve what you are trying to do.
import java.util.Scanner;
public class Assignment2 {
public static void main(String[] args) {
int sum = 0, minNumber = 0, nCount = 0, countEvenIntegers = 0;
Scanner sc = new Scanner(System.in);
while (true) {
int input = sc.nextInt();
if (input == 0) {
break;
}
sum += input;
nCount += 1;
}
System.out.println("The minimum integer is " + minNumber);
System.out.println("The count of integers is " + nCount);
System.out.println("The sum of positive integers is " + sum);
System.out.println("The count of even integers in the sequence is " + countEvenIntegers);
}
}
Note that I've not added the minimum interger and count of even intergers for you to complete.
Not quite sure what you are doing in your code since you are not doing any operations on the variables you are outputting, and thus should not expect the output to be any other than 0.
Also, your inner classes are really weird.
Here is an example (based on your code) that does what you want. Plenty of ways of achieving your goal, but I think this is simple enough:
import java.util.Scanner;
import java.util.*;
public class Assignment2{
private static final Scanner input = null;
private static int n;
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
int sum=0, minNumber=0, nCount=0, countEvenIntegers=0, sumPositive = 0;
Scanner sc = new Scanner(System.in);
List<Integer> numbers = new ArrayList<Integer>();
while(true) {
int i = sc.nextInt();
if(i == 0) {
break;
}
numbers.add(i);
}
if(numbers.size() > 0) {
minNumber = numbers.get(0);
}
for (int number : numbers) {
sum += number;
if(minNumber > number) {
minNumber = number;
}
if(number % 2 == 0) {
countEvenIntegers++;
}
if(number > 0 ) {
sumPositive += number;
}
}
nCount = numbers.size();
System.out.println("The minimum integer is " + minNumber + "\nThe count of integers is "
+ nCount + "\nThe sum of positive integers is " + sumPositive + "\nThe count of even integers in the sequence is " +
countEvenIntegers + "\nThe total sum is " + sum);
}
}

Java return (value) error

I tried different things in my code, but I always get errors.
The instructions for the program is that I need to have a function (besides from main) that receives arguments for an array of integer values and a second argument telling the desire value to look in the array by the user.
It must also return how many times the desire value is repeated on the array.
The errors are related to the counter and also some are in the main function.
I think I am not returning the counter value correctly.
This is my current code:
import java.util.Scanner;
import java.util.Arrays;
public class ArregloBusqueda2
{
static int findRepetition(int listOfValues[], int targetValue, int counter)
{
int i;
boolean found = false;
for(i=0; i<listOfValues.length; i++)
{
while((counter < listOfValues.length))
{
if(listOfValues[i] == targetValue)
{
counter = counter + 1;
}
}
}
return counter;
}
public static int main(String[] args)
{
Scanner input = new Scanner (System.in);
int targetValue;
int listOfValues[] = {1,6,3,8,5,8,3,4,8,3};
System.out.println("Please enter the desire number to look for: ");
targetValue=input.nextInt();
findRepetition(targetValue, counter);
if(counter != 0)
{
System.out.println("The frequency of the number " + targetValue + " is: " + counter);
}
else
{
System.out.println ("The number " + targetValue + " is not contained in the array list");
}
}
}
Multiple issues in your code.
public static int main(String[] args) should be public static
void main(String[] args)
findRepetition takes three arguments,
but you are passing two agruments
counter variable is not declared
Logical flaw, while((counter < listOfValues.length)) will keep on executing if counter value is less than listOfValues.
static int findRepetition(int listOfValues[], int targetValue) {
int i;
int counter = 0;
for (i = 0; i < listOfValues.length; i++) {
if (listOfValues[i] == targetValue) {
counter = counter + 1;
}
}
return counter;
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int targetValue;
int listOfValues[] = { 1, 6, 3, 8, 5, 8, 3, 4, 8, 3 };
System.out.println("Please enter the desire number to look for: ");
targetValue = input.nextInt();
int counter = findRepetition(listOfValues, targetValue);
if (counter != 0) {
System.out.println("The frequency of the number " + targetValue + " is: " + counter);
} else {
System.out.println("The number " + targetValue + " is not contained in the array list");
}
}
You made your method accept three parameters.
static int findRepetition(int listOfValues[], int targetValue, int counter)
Ask yourself - do you want to "pass in a counter", or only return it? The instructions say the latter.
When you call this method, you are not providing the correct inputs.
findRepetition(targetValue, counter);
What about the listOfValues? You want to findReptition on listOfValues for targetValue, right? So provide the correct parameters into that method call.
Again, you likely do not need the counter passed-in. Because Java is always pass-by-value
Rather, you want to return counter, as you have written. You are looking for this.
int counter = findRepetition(listOfValues, targetValue);
Fixing the remainder of the code is a learning exercise.
You are not calling findRepetition() with required parameters, findRepetition method takes 3 arguments, but you are passing only 2 arguments.

Recursive methods which exclude each other?

I am trying to write a method that calculates the sum of odd integers between 1 and a given positive integer n, without using anything else than if statements (sheesh!). It worked out just fine until I decided to also create a method that would ask recursively for the number until it was positive and use it to get n.
Now my program outputs the correct results until I enter a negative number. It then asks for a postive one until I enter one and it outputs 0, the value I initialised the variable val with.
I'm not sure where the logic error is. Could you please take a look? I'm sure it's something obvious, but I guess I have just reached the end of my wits today. Thanks!
package oddsum;
import java.util.Scanner;
public class Oddsum {
public static int oddSum(int n){
int val=0;
if(n>1){
if(n%2==0){
val=n+oddSum(n-1);
}else{
val=oddSum(n-1);
}
}
return val;
}
public static int request(int n){
Scanner in= new Scanner(System.in);
System.out.println("Give me a positive integer: ");
n=in.nextInt();
if (n<0){
System.out.println("I said positive! ");
request(n);
}
return n;
}
public static void main(String[] args) {
int val=0;
int n=request(val);
System.out.println(oddSum(n));
}
}
You should remove input parameter from your request() method. Because your negative input is carried out through the recursive call.
public class Oddsum {
public static int oddSum(int n) {
int val = 0;
if (n > 1) {
if (n % 2 == 0) {
val = n + oddSum(n - 1);
} else {
val = oddSum(n - 1);
}
}
return val;
}
public static int request() {
Scanner in = new Scanner(System.in);
System.out.println("Give me a positive integer: ");
int n = in.nextInt();
if (n < 0) {
System.out.println("I said positive! ");
return request();
}
return n;
}
public static void main(String[] args) {
int n = request();
System.out.println(oddSum(n));
}
}
Output;

How to add a long integer to existing program

The code works. But, I need to include long integers. How can I do that? I've tried a million things. I'm not good at this either so it takes me 5 times longer to get a simple code. Please help.
import java.util.Scanner;
public class Exercise2_6M
{
public static void main(String[] args)
{
// Create a Scanner
Scanner input = new Scanner(System.in);
// Enter amount
System.out.print("Enter an integer:");
int integer = input.nextInt();
// Calculations
int rinteger = Math. abs (integer);
int sum = 0;
int i=0;
while(rinteger / Math.pow(10,i) > 0)
{
sum+=getDigit(rinteger,i);
i++;
}
// Display results
System.out.println("Sum all digits in " + integer + " is " + sum);
}
public static int getDigit(int num, int power)
{
return (num % (int)Math.pow(10,power+1)) / (int)Math.pow(10,power);
}
}
Read the input value as a string and then use the BigInteger class to perform calculations with very large values​​.
A recursive solution can be much leaner:
import java.util.Scanner;
public class Exercise2_6M
{
public static void main (String [] args)
{
Scanner input = new Scanner (System.in);
System.out.print ("Enter an long:");
long lng = input.nextLong ();
int sum = getDigitSum (lng);
System.out.println ("Sum all digits in " + lng + " is " + sum);
}
public static int getDigitSum (long num)
{
if (num < 10L) return (int) num;
else return ((int)(num % 10)) + getDigitSum (num/10L);
}
}

Categories