Java input array based on if/else using recursion only - java

I've been given the following homework...
We have bunnies standing in a line, numbered 1, 2, ... n
The even numbered bunnies (2, 4, ..) have the normal 2 ears.
The odd numbered bunnies (1, 3, ..) have 3 ears.
Recursively return the number of "ears" in the bunny line 1, 2, ... n (without loops or multiplication).
I tried first with loops:
import java.util.Scanner;
public class BunnyEars {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Enter number of bunnies: ");
int a = in.nextInt();
int [] bunnies = new int [a];
//for loop(non-recursive method)
for(int i=0;i<bunnies.length;i++)
{
if(i%2==0)
{
bunnies[i]=2;
}
else
{
bunnies[i]=3;
}
System.out.println("Bunny ["+i+"] : "+bunnies[i]+" ears");
}
}
}
However, after removing the loop, I'm not sure how to increment the array number as shown here:
import java.util.Scanner;
public class BunnyEars {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Enter number of bunnies: ");
int a = in.nextInt();
int [] bunnies = new int [a];
Ears(bunnies);
// TODO Auto-generated method stub
}
public static void Ears(int [] bunnies) {
int x =0;
bunnies[x]=bunnies[x+1];
if(x<bunnies.length)
{
if(x%2==0)
{
bunnies[x]=2;
}
else
{
bunnies[x]=3;
}
}
System.out.println("Bunny ["+x+"] : "+bunnies[x]+" ears");
}
}
I will keep getting just "bunny[0]: 2 ears". There is another bunny question on stackoverflow but the output desired is different. Been searching around but can't seem to find a similar question. Any ideas?

I'd go with the pseudocode below. I don't want to write real code because it's a homework assignment and you're supposed to learn from trial and error.
So here is the pseudocode. You'll have to figure out how to end the recursion.
int ears(int[] bunnies) {
return Ears(bunnies, 0);
}
int ears(int[] bunnies, int index) {
int ears = countEars(bunnies, index);
return ears + ears(bunnies, index + 1);
}

public class BunnyEars {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Enter number of bunnies: ");
int a = in.nextInt();
printEar(a - 1);
}
public static void printEar(int i) {
if (i > 0) {
printEar(i - 1);
}
System.out.println("Bunny [" + i + "] : " + ((i % 2 == 0) ? 2 : 3) + " ears");
}
}

Related

Reverse a three digit int; if there is a leading zero in the output it shoud be left out

First of all, a similar queston has already been asked here: How to calculates the number by reversing its digits, and outputs a new number
I am at the beginning of the Java trail at [Jetbrains/hyperskill][1] and the accepted
[1]: https://hyperskill.org/learn/step/2217
answer to the above question is not yet taught at Jetbrains, that's why asking this question.
Here is what I have:
import java.util.Scanner;
public class Main3 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter your number: ");
int a = scanner.nextInt();
int hundreds = (a % 1000) / 100;
int tens = (a % 100) / 10;
int ones = a % 10;
System.out.println(ones + "" + tens + "" + hundreds);
}
}
To be clear, if the input is 320 for instance, the output should be 23, not 023.
Just to clarify, the only subjects taught at this level is Types and variables, Naming variables, Arithmic operations, Increment and decrement, Strings, Basic literals, Printing data, Scanning the input.
you can convert the hundreds tens and ones into a integer. and print this one.
int number = 100*hundreds + 10*tens + ones;
System.out.println(number);
I saw the problem and the below solution should be good to handle the cases you mentioned
public static void reverse(int num) {
int rev=0;
while(num>0) {
int rem = num%10;
rev=rev*10+rem;
num/=10;
}
System.out.println(rev);
}
How about getting benefit from StringBuilder?
import java.util.Scanner;
class Main {
public static void main(String[] args) {
try (Scanner scanner = new Scanner(System.in)) {
StringBuilder stringBuilder = new StringBuilder(String.valueOf(scanner.nextInt())).reverse();
if (stringBuilder.charAt(0) == '0') {
stringBuilder.deleteCharAt(0);
}
System.out.println(stringBuilder.toString());
} catch (Exception e) {
e.printStackTrace();
}
}
}
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
var n = scanner.nextInt();
System.out.print(n / 100 + 10 * (n / 10 % 10) + 100 * (n % 10));
}
}
Credit for this answer goes to #OlgaAI

How to add numbers to even and odd lists in java?

I want to make a program that will read from the keyboard a sequence of numbers and
will create a dynamic list of even numbers and another dynamic list of odd numbers, and I have a problem, the even numbers are added to the even list and the odd ones to the odd list, but the display does not display the numbers I added.
import java.io.IOException;
import java.util.ArrayList;
import java.util.Scanner;
public class lab13_1 {
static ArrayList<lab13_1> odd = new ArrayList<>();
static ArrayList<lab13_1> even = new ArrayList<>();
static int number;
public lab13_1(int number) {
this.number=number;
}
public String toString()
{
return "number"+number;
}
static void calc() {
try {
Scanner cin = new Scanner(System.in);
System.out.println("How many numbers do you want to add : ");
int nr = cin.nextInt();
for (int i = 0; i < nr; i++) {
System.out.println("<<< nr. " + (i + 1) + " >>>");
number = cin.nextInt();
if (number % 2 == 0) {
even.add(new lab13_1(number));
} else odd.add(new lab13_1(number));
}
} catch (Exception e) {
e.printStackTrace();
}
}
static void afish(){
System.out.println("Nr. odd");
for(lab13_1 i : odd) {
System.out.println(i.toString());
}
System.out.println("Nr. even");
for(lab13_1 i : even) {
System.out.println(i.toString());
}
}
public static void main(String[] args) throws Exception {
calc();
afish();
}
}
the data it displays :
How many numbers do you want to add :
5
<<< nr. 1 >>>
1
<<< nr. 2 >>>
2
<<< nr. 3 >>>
3
<<< nr. 4 >>>
4
<<< nr. 5 >>>
5
Nr. odd
number5
number5
number5
Nr. even
number5
number5
Who knows why it doesn't display numbers normally?
It's because your variable number is static. Remove static keyword and it should be fine.
int number;
You are using a static variable.
Static means that it does not depend by the instance of the class..
Usually you use static variables for counting the instances of an object or the nr. of times a function is called.
For e.g.
class TestStatic
{
public static int count = 0;
int mNumber;
void doSomething(int number)
{
mNumber=number;
count++;
}
int getNumber()
{
return mNumber;
}
}
Using it
public static void main()
{
List<TestStatic> tsList = new ArrayList<TestStatic>();
for(int i=0; i<5; i++)
{
TestStatic ts = new TestStatic();
ts.doSomething(i);
tsList.add(ts);
}
for(TestList ts : tsList)
{
System.out.println("Count = " + ts.count + "mynumber = " + ts.getNumber() );
}
}
In the output you will see count always at 5, number 0,1,2,3,4
This should let you explain how to use static variables.
Note that you should access static variables with
TestStatic.count
not with the instance.
P.S. code should run but i've not tested it
This is a cleaner answer to your desired goal
public class lab13_1 {
static ArrayList<Integer> odd = new ArrayList<>();
static ArrayList<Integer> even = new ArrayList<>();
static int number;
static void calc() {
try {
Scanner cin = new Scanner(System.in);
System.out.println("How many numbers do you want to add : ");
int nr = cin.nextInt();
for (int i = 0; i < nr; i++) {
System.out.println("<<< nr. " + (i + 1) + " >>>");
number = cin.nextInt();
if (number % 2 == 0) {
even.add(number);
} else odd.add(number);
}
} catch (Exception e) {
e.printStackTrace();
}
}
static void afish() {
System.out.println("Nr. odd");
for (Integer i : odd) {
System.out.println(i.toString());
}
System.out.println("Nr. even");
for (Integer i : even) {
System.out.println(i.toString());
}
}
public static void main(String[] args) throws Exception {
calc();
afish();
}
}

Getting Odd numbers from Array

I've been working on this program and am currently stuck. The HW prompt is to prompt a user to input numbers, save it as an array, find the number of odd numbers & the percentages then display those values back to the user.
Currently I am trying to write to part of the code that finds the percentage of the odd numbers in the array but the return isn't displaying and i just cant figure it out. Any ideas? Thank you!
import java.util.*; // import java course for Scanner class
public class Integers {
public static void main(String[] args) {
Scanner console = new Scanner(System.in);
System.out.println("Please input a series of numbers");
int inputs = Integer.parseInt(console.next());
int[] arraysize = new int[inputs];
Oddvalues(arraysize);
}
public static int Oddvalues (int[] size) {
int countOdd = 0;
for (int i = 1; i < size.length; i++) {
if(size[i] % 2 != 0) {
i++;
}
}
return countOdd;
}
}
Consider the following code, which appears to be working in IntelliJ locally. My approach is to read in a single line from the scanner as a string, and then to split that input by whitespace into component numbers. This avoids the issue you were facing of trying to directly create an array of integers from the console.
Then, just iterate over each numerical string, using Integer.parseInt(), checking to see if it be odd.
public static void main(String[] args) {
Scanner console = new Scanner(System.in);
System.out.println("Please input a series of numbers");
String nextLine = console.nextLine();
String[] nums = nextLine.split(" ");
int oddCount = 0;
for (String num : nums) {
if (Integer.parseInt(num) % 2 == 1) {
++oddCount;
}
}
double oddPercent = 100.0*oddCount / nums.length;
System.out.println("Total count of numbers: " + nums.length + ", percentage odd: " + oddPercent);
}
In the function Oddvalues you promote i instead of promoting countOdd. And the loop should start from 0 not 1.
Try this
import java.util.*;
import java.lang.*;
import java.io.*;
public class OddVals{
public static void main(String[] args) throws java.lang.Exception {
Scanner sc = new Scanner(System.in);
int[] array = new int[sc.nextInt()]; // Get the value of each element in the array
System.out.println("Please input a series of numbers");
for(int i = 0; i < array.length; i++)
array[i] = sc.nextInt();
System.out.println("Number of Odds:" +Oddvalues(array));
printOdd(array);
}
public static int Oddvalues (int[] size) {
int countOdd = 0;
for (int i=0; i < size.length; i++){
if(size[i]%2 != 0)
++countOdd;
}
return countOdd;
}
public static void printOdd(int[] arr)
{
for(int i=0;i<arr.length;++i)
{
if(arr[i]%2==1)
System.out.print(arr[i]+" ");
}
}
import java.util.*; // import java course for Scanner class
public class Integers {
public static void main(String[] args) {
List<Integer> intList = new ArrayList<Integer>();
Scanner console = new Scanner(System.in);
System.out.println("Please input a series of numbers");
while (console.hasNext())
{
String str = console.next();
try
{
if(str.equals("quit")){
break;
}
int inputs = Integer.parseInt(str);
System.out.println("the integer values are" +inputs);
intList.add(inputs);
}
catch (java.util.InputMismatchException|NumberFormatException e)
{
console.nextLine();
}
}
console.close();
double d = Oddvalues(intList);
System.out.println("the percent is" +d);
}
public static double Oddvalues (List<Integer> list) {
int count = 0;
for( Integer i : list)
{
if(!(i%2==0))
{
count++;
}
}
double percentage = (Double.valueOf(String.valueOf(count))/ Double.valueOf(String.valueOf(list.size())))*100;
return percentage;
}
}
If this helps

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;

Perfect Numbers Display Java

I have the following question for Homework
If a number is equal to the sum of all of its factors except itself, it is a perfect number. For example, 6 is a perfect number since 6 = 1 + 2 + 3.
Write a program that takes an input number and displays all perfect numbers up to and including that number.
and this is what I have so far
import java.util.*;
public class perfectnumbers
{
public static void main(String[] args){
Scanner console = new Scanner(System.in);
int externalNumber;
int internalNumber;
int internalTotal = 0;
System.out.println("Input Number");
externalNumber = console.nextInt();
while (externalNumber > 0) {
internalNumber = externalNumber;
while (internalNumber > 0) {
internalNumber = internalNumber - 1;
internalTotal = internalNumber + internalTotal;
}
if (internalTotal == externalNumber) {
System.out.println(internalTotal);
}
externalNumber = externalNumber - 1;
internalTotal = 0;
}
}
}
But for some Reason when ever I enter a number only 3 gets outputted... Can anyone help?
Perfect numbers (like other perfect things) are very scarce ones
https://oeis.org/A000396
they are (within the int range):
6, 28, 496, 8128, 33550336
(only three more 8589869056, 137438691328, 2305843008139952128 when working with long).
So you can implement it like that:
private static int[] perfectNumbers = new int[] {
6, 28, 496, 8128, 33550336
};
private static void displayPerfects(int upTo) {
for (int item : perfectNumbers)
if (item > upTo)
break;
else {
System.out.print(item);
System.out.println();
}
}
...
public static void main(String[] args) {
...
System.out.println("Input Number");
...
externalNumber = console.nextInt();
...
displayPerfects(externalNumber);
}
Please note, that efficiency really matters in your case, e.g. how much time does it take if your're given, say, 2000000000? All you have to do is to test at most five values.
You never check for a factor. Do something like this:
while (externalNumber > 0) {
internalNumber = externalNumber-1; //Make sure to subtract one here
while (internalNumber > 1) { //Change this to 1 so you don't divide by 0
internalNumber = internalNumber - 1;
if (externalNumber%internalNumber==0){ //Check for factor
internalTotal = internalNumber + internalTotal;
}
}
if (internalTotal == externalNumber) {
System.out.println(internalTotal);
}
externalNumber = externalNumber - 1;
internalTotal = 0;
}

Categories