Recursive methods which exclude each other? - java

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;

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);
}
}

My code isn't displaying the required result for kaprekar number

I applied all of my brain but can't figure out what to do for making a program, that finds out whether a number is kaprekar or not by using only 2 functions int countdDigits(int ) and void check(int ) except main(), display the correct result
import java.util.*;
class kaprekar
{
private int countDigit(int a)
{
int count = 0;
while(a>0)
{
a/=10;
++count;
}
return count;
}
private void check(int n)
{
int a = countDigit(n);
int d = (int)Math.pow(10, a);
int sum = (a/d) + (a%d);
if(n==sum)
System.out.println("It is a kaprekar number");
else
System.out.println("It is not a kaprekar number");
}
public static void main()
{
Scanner sc=new Scanner(System.in);
kaprekar ob=new kaprekar();
System.out.println("Enter a number to check");
int num = sc.nextInt();
ob.check(num);
}
}
required result:
Enter a number to check
45
It is a kaprekar number
actual results:
Enter a number to check
45
It is not a kaprekar number
I think your problem is here
int a = countDigit(n);
int d = (int)Math.pow(10, a);
int sum = (a/d) + (a%d);
You divided the number of digits with d. I think you need to divide n with d, not a.
For Kaprekar you have to check if a sum of parts of the square number in question is the same as the number.
e.g. 45 --> 45²=2025 --> 20+25=45
following should do:
import java.util.Scanner;
public class KaprekarCheck {
private static boolean isKaprekar(int n)
{
String square = Long.toString(n*n);
for (int i=1; i< square.length(); i++) {
System.out.println("i="+i+" len="+square.length());
int num1 = Integer.parseInt(square.substring(0, i));
int num2 = Integer.parseInt(square.substring(i, square.length()));
System.out.println("i="+i+" len="+square.length()+" num1="+num1+" num2="+num2);
if (num1+num2==n) {
return true;
}
}
return false;
}
public static void main(String[] args) {
int num = 9;
if(isKaprekar(num))
System.out.println("It is a kaprekar number");
else
System.out.println("It is not a kaprekar number");
}
}

There is something wrong in my code but i'm not sure what it is?

I'm trying to print the sum of digits of the numbers that the user inputs,
what's wrong in my code? it appears to me that sum is underlined in the S.O.P..
but why is that? and how can I fix it?
package assignment7;
import java.util.Scanner;
public class Assignment7_4_5 {
public static void main(String[] args) {
Scanner input= new Scanner (System.in);
System.out.print("Enter a number: ");
int number=input.nextInt();
System.out.println("sum: "+sumDigits (sum));
}
public static int sumDigits(int sum) {
int number = 0;
while (number > 0) {
sum = sum + number % 10;
number = number / 10;
}
return sum;
}
}
You need to change sumDigits(sum) to sumDigits(number) because number is the variable that you are passing to the method, the variable sum is not even declared before using the method sumDigits. Also in the function, the while loop will never execute because number is set to zero and the condition is (number > 0) which is never true.
You have sum and number the wrong way around. You need to pass in number, as this is what you get from the user. Sum needs to be initialised to 0 in sumDigits, not number. Then you're incrementing sum and dividing down number, returning sum once you're finished. You also don't then skip over your while loop!
package assignment7;
import java.util.Scanner;
public class Assignment7_4_5 {
public static void main(String[] args) {
Scanner input= new Scanner (System.in);
System.out.print("Enter a number: ");
int number=input.nextInt();
System.out.println("sum: "+sumDigits (number));
}
public static int sumDigits(int number) {
int sum = 0;
while (number > 0) {
sum = sum + number % 10;
number = number / 10;
}
return sum;
}
}

Why won't my program loop correctly?

I'm new to programming and I'm making a guessing game where the program randomly generates a number between 1 and 10, the user then is asked to guess what the number is, the user should be able to keep guessing until he guesses correctly and the system asks them if they want to play again,
In my code I've printed the number that the system has randomly generated so that it is quicker to complete the game whilst testing. When I try and execute the program and enter the number that the system has generated the message that they are correct and asking if they want to play again does not come up.
Any help would be greatly appreciated!
Thank you in advance,
(Also, anything wrong with this question just tell me, it's my first time asking on here)
Here is my code,
import java.util.Scanner;
import java.util.Random;
public class GuessingGame1 {
public static int randomizer() {
Random rand = new Random();
int num = rand.nextInt(10)+1;
System.out.println(num);
int count = 0;
return num;
}
public static int userInput() {
System.out.println("I've thought of a number between 1 and 10");
System.out.println("Enter your guess...");
Scanner scan = new Scanner(System.in);
int guess = scan.nextInt();
return guess;
}
public static String compare() {
int count = 0;
String result = null;
if (userInput() == randomizer()) {
System.out.println("You guessed it - I was thinking of " + randomizer());
count++;
result = "It took you " + count + " guesses.";
return result;
}
else if (userInput() > randomizer()) {
result = "Lower!";
count++;
return result;
}
else if (userInput() < randomizer()) {
result = "Higher";
count++;
}
return result;
}
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
Scanner scanLine = new Scanner(System.in);
String playAgain = "";
do {
randomizer();
do {
userInput();
compare
} while (userInput() != randomizer());
System.out.println("Play again? Yes/No");
playAgain = scanLine.nextLine();
} while (playAgain.equalsIgnoreCase("yes") || playAgain.equalsIgnoreCase("y"));
}
}
The problem is that you call twice to Randomizer!
call randomizer once as parameter to compare and return boolean from compare for a match.
You must change your methods something like this
public static String compare(int a,int b) {
int count = 0;
String result = null;
if (a == b) {
System.out.println("You guessed it - I was thinking of " + b);
count++;
result = "It took you " + count + " guesses.";
return result;
}
else if (a > b) {
result = "Lower!";
count++;
return result;
}
else if (a < b) {
result = "Higher";
count++;
}
return result;
}
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
Scanner scanLine = new Scanner(System.in);
String playAgain = "";
int a;
int b;
do {
do {
a=userInput();
b= randomizer();
System.out.println(compare(a,b));
} while (a != b);
System.out.println("Play again? Yes/No");
playAgain = scanLine.nextLine();
} while (playAgain.equalsIgnoreCase("yes") || playAgain.equalsIgnoreCase("y"));
}
}
you have left the () in compare and the count will always be zero as it is been initialized when the compare function is called.

Get int variables within a String method Java

This is homework. Just going to put that out there. I feel it is best to show my code first and explain what I'm attempting to do
import java.util.Scanner;
public class Question1 {
public static void main(String[] args){
int length, odd, even, largest;
int n = getNumber();
length=odd=even=largest=initialize();
String sequence=createSequence(n, largest, odd, even, length);
displaySequence(sequence);
displayStatistics(largest, length, odd, even);
}
private static int getNumber(){
Scanner kb = new Scanner(System.in);
System.out.println("Enter the value of the number: ");
int number = kb.nextInt();
return number;
}
private static int initialize(){
return 0;
}
public static String createSequence(int n, int largest, int odd, int even, int length){
String sequence="";
sequence+=n+" ";
while (n!=1){
n = (n%2==0) ? n/2 : 3*n+1;
System.out.print(", "+n);
sequence+=n+" ";
if(n%2==0){ even++;
}else{ odd++;}
if(n>=largest){ largest = n;
}
length++;
}
return sequence;
}
private static void displaySequence(String sequence){
System.out.println(sequence);
}
public static String displayStatistics(int length, int even, int odd, int largest){
String nil = "";
System.out.println("The largest number in the sequence was "+largest);
System.out.println("The length of the sequence was "+length);
System.out.println("There were "+odd+" odd numbers");
System.out.println("There were "+even+" even numbers");
return nil;
}
}
I need attempting to display the largest number in the sequence, the length of the sequence, how many even numbers there were in the sequence and how many odd numbers there were in the sequence. But since I cannot return an int value in the createSequence method, I cannot get the new values for each statistic. Preventing me from displaying said statistics. How would I access these new variables to be used in the final method?
Note:
Requirements:
Declare variables in main
Initialize variables in Initialize()
createSequence (Create the sequence)
displaySequence (Then display the sequence in a separate method)
finally displayStatistics i.e. length, evens, odds, largest (in its own method), this is the one that's troubling me
Try reimplementing your code off of my basecode
public class Question{
public class NumberStats {
int len;
boolean isOdd;
}
private ArrayList<NumberStats> stats = new ArrayList<>();
public static void main(String[] args){
Question q = new Question();
Scanner kb = new Scanner(System.in);
String number = "";
do {
System.out.println("Enter a series of numbers or q to quit: ");
number = kb.next();
q.stats.add(q.parseNumber(number));
} while (number.equals("q")==false);
q.printSummary();
}
private void printSummary(){
int oddCount = 0;
int evenCount = 0;
int longestNumber = 0;
for (NumberStats s : stats){
if (longestNumber<s.len){
longestNumber = s.len;
}
if (s.isOdd){
oddCount+=1;
} else {
evenCount+=1;
}
}
System.out.println(String.format("Longest number length was : %i, Odd Numbers: %i, Even Numbers: %i",longestNumber,oddCount,evenCount));
}
private NumberStats parseNumber(String number){
NumberStats stats = new NumberStats();
Integer lastNumber = Integer.parseInt(String.valueOf(number.charAt(number.length()));
stats.isOdd = true;
if (lastNumber%2==0){
stats.isOdd = false;
}
stats.len = number.length();
return stats;
}
}
Your teacher may be a bit more impressed if you created a Sequence class. The class attributes would be the stats (which could be accessed via getter methods). The createSequence method would become the constructor. And you could implement a toString method to return a string representation of the contents.

Categories