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.
Related
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);
}
}
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.
Question: Write a method that takes as input a variable number of integers. The method should return the average of the integers as a double. Write a full program to test the method.
That code below creates an array of 10 integers and finds their average. However, I need it to create a variable number of arguments (int...a) where any number of integers entered can be averaged. Can someone help me.Thanks.
My code:
package average.pkgint;
import java.util.Scanner;
public class AverageInt {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
int [] number = new int [10];
Scanner b = new Scanner(System.in);
System.out.println("Enter your 10 numbers:");
for (int i = 0; i < number.length; i++) {
number[i] = b.nextInt() ;
}
System.out.println("The average is:"+Avnt(number));
}
public static int Avnt(int [] a){//declare arrays of ints
int result = 1;
int sum = 0;
//iterate through array
for (int num : a) {
sum += num;
}
double average = ( sum / a.length);//calculate average of elements in array
result = (int)average;
return result;
}
}
This is a way of getting as many variables as you want to a method and going through them all:
public static void testVarArgs(int... numbers){
for(double u: numbers) {
System.out.println(u);
}
}
If you don't want to read the number of integers as the first input you can declare a stack in stead of an array
Stack<Integer> numbers=new Stack<>()
and then you can add the numbers with the add method.
Just change your method declaration to a variable length parameter:
public static int Avnt(int ... a){//declare variable int arguments
When you use a variable length parameter, you supply the values in the method invocation. For example,
System.out.println(Avnt(1,2,3));
System.out.println(Avnt(1,2,3,4,5,6,9,9,9,10,10));
Actually, this looks like it meets your requirements. Just add method calls in your main() similar to these.
I have a method outside of the main method that averages. At the end of the main I am calling on that averaging method. I am not understaning the propper way to
1. use variables I declare with other methods in this program. for example the sum which is defined in the calculate_average method.
or
The sum which is defined in the main method.
Please show me
how to interchange variables in and out of the main method. interchangeably between methods that are not in main.
call on a method outside of main in main to calculate the average.
Here is my current code.
import java.util.ArrayList;
import java.util.Scanner;
class programTwo
{
private static Double calculate_average( ArrayList<Double> myArr )
{
Double Sum = 0.0;
for (Double number: myArr)
{
Sum += number;
}
}
public static void main( String[] args )
{
Scanner scan = new Scanner(System.in);
ArrayList<Double> myArr = new ArrayList<Double>();
double Sum = 0;
int count = 0;
System.out.println("Enter a number to be averaged, repeat up to 20 times:");
String inputs = scan.nextLine();
while (!inputs.matches("[qQ]") )
{
if (count == 20)
{
System.out.println("You entered more than 20 numbers, you suck!");
break;
}
Scanner scan2 = new Scanner(inputs); // create a new scanner out of our single line of input
myArr.add(scan2.nextDouble());
count += 1;
System.out.println("Please enter another number or press Q for your average");
inputs = scan.nextLine();
}
Double average = calculate_average(myArr);
System.out.println("Your average is: " + average);
return Sum / myArr.size();
}}
You have this at the end of main:
return Sum / myArr.size();
You need to move it to calculate_average:
private static Double calculate_average( ArrayList<Double> myArr )
{
Double Sum = 0.0;
for (Double number: myArr)
{
Sum += number;
}
return Sum / myArr.size();
}
Given that main is void and an average makes no sense as an exit code even if it weren't, I'm assuming that is some kind of typographical error.
Some code review
Local variables should start with a lower case letter. So sum, not Sum
You can use the primitive double instead of a Double object. Using the object will cause boxing/unboxing overhead.
Indent your while loop and its contents by four more spaces so the loop beginning aligns vertically with the code above it because it's in the same block (the method's block).
Split those last 2 braces into separate lines
Line up the last two braces vertically with the matching opening brace
You've started by creating your calculate_average method, but continue breaking up main. It's too long. Too much is going on there.
Change if (count == 20) to if (count >= 20). Harder to mess up, then.
i think you have static method,
so you can call them bye using className.MethodName Directly.
Just Declare your method as public and you can call them outside also.
programTwo.calculate_average(myArr)
No need to create object for calling static methods.
There's nothing I can see wrong with your code, except you are missing a return statement in your calculate_average method.
Also, if you name a method calculate_average, it should return the average not the sum.
Try this:
private static Double calculate_average( ArrayList<Double> myArr )
{
Double sum = 0.0;
for (Double number: myArr)
{
sum += number;
}
return sum/myArr.size(); // added return statement
}
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.