How to recurse back to start? - java

I'm a noob programmer, but I've been stuck on this one bit of code. How do you recurse back to start? I've tried several different methods but they all either take a ridiculous amount of code or don't work properly. I've been trying to implement this "simple" piece of code in all of my programming assignments, but it hasn't been working out. Thanks!
p.s. I've already finished the assignment. I'm just trying to make it more "complete".
public class OddProduct {
public static void main(String[] args) {
//Inputs from user
System.out.println("Enter an odd number");
Scanner input_odd = new Scanner(System.in);
int odd = input_odd.nextInt();
int oddproduct = 1;
//Multiplies all odd integers
for (int counter = 1; counter <= odd; counter = counter + 2){
oddproduct = oddproduct * counter;
}//end of for- loop
System.out.printf("\nThe product of all the odd integers up to %d is %d\n",
odd, oddproduct);
/* MY NOTES FOR RECURSE
if (odd%2 == 1){ proceed normally}
else if (odd%2 != 1) { HOW TO LOOP BACK???}
else { println = "Application closed"}
*/
}//end of main method
}//end of OddProduct class

Based upon your Notes I think this is what you require
Scanner input_odd = new Scanner(System.in);
int odd = 0;
while (odd % 2 != 1) { // fails first time && if user enters even number
System.out.println("Enter an odd number");
odd = input_odd.nextInt();
}

Related

how can i check if the number is perfect square by not using math.sqrt

i want to make a program which related to this question:
An integer that can be expressed as the square of another integer is called a perfect square, such as 4,9,16,25, etc. Write a progran that checks if a number is a perfect square.
I did built something goes like:
import java.util.Scanner;
class Q3{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
int num = 0;
int a = 0;
System.out.println("Type a number to check if it has square");
num = sc.nextInt();
for(a = 1;a<num;a++){ }
if (a*a == num){
System.out.println("Ok");
break;
}
else if (a*a != num){
System.out.println("Not ok");
}
}
}
So it doesn’t give what i want when i run it. What should i change or add ?
I think your for loop interpretation might be wrong, I made up something that might just work. Give this code a try.. You can make the method return a boolean too if you want.
static void perfectSquare(int number) {
for (int i = 1; i < i * number; ++i) {
// 'i' is the divisor, making sure
// it is equal to the quotient
if ((number % i == 0) && (number / i == i)) {
System.out.println(i);
}
}
If you want to brute force every number then you are on the right track but you should only print "Not ok" if all numbers in the loop have failed otherwise you may have a perfect square but "Ok" will be hidden within many "Not ok" lines. Also there is nothing in your for loop so the if statement always checks if 0*0 == num.
This looks like it may be a homework question so I won't give a full answer for you but think about how you can make this more efficient.
If you have found an integer number that matches do you need to keep going?
Do you need to check every number? (a starting point may be following the principles of a binary search)
I ended up like this:
import java.util.Scanner;
class Q3{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
int num = 0;
int a = 0;
int b = 0;
System.out.println("Type a number to check if it has square");
num = sc.nextInt();
for(a = 1;a<num;a++){
if (a*a == num){
b = 1;
break;
}
}
if(b==1){
System.out.println("Perfect Square");
}
else {
System.out.println("Not ok");
}
}
}
Thanks for support !

How to create an addition loop of random numbers?

After writing 1 on scanner I want a random dice number generated and after pressing 1 again I want another random number generated but now I want it added with previous number. I want to make a loop, I want to keep pressing 1 and keep adding random numbers till I reach a certain number.
Thank you.
import java.util.Random;
import java.util.Scanner;
public class dice {
public static void main(String[] args) {
// TODO Auto-generated method stub
for (int k = 0; k < 100; k++) {
Scanner scan = new Scanner(System.in);
int s = scan.nextInt();
System.out.println(s);
int previous = s;
if (s == 1) {
Random ran = new Random();
int n = ran.nextInt(6) + 1;
System.out.print(n);
int next;
while (true) {
next = scan.nextInt();
if (next == 1) {
System.out.println(previous);
}
previous = n + 10;
}
}
}
}
}
Define previous outside the for loop, and replace
int previous = s;
previous = n + 10;
with
previous += s;
previous += n + 10;
Scanner sc=new Scanner(System.in);
int sum=0;
for(;;)
{
if(sc.nextInt()==1)
{
int num = (int)(Math.random()*6); // using the pre-defined random function in java.lang.Math class
System.out.println("Dice Value: "+num);
sum+=num; // shorthand adding the number for each iteration
}
//if(sum>100)
// break;
//if statement to check if value of sum is greater/lesser than a specific number
}
System.out.println("Final Answer: "+sum)
Something like this might work (not yet tested): an infinite loop that can be terminated as per choice.
If you are looking for a way that the program works as soon as you physically press the '1' key on your keyboard, without having to press the enter key, something like a keyevent might work:
https://docs.oracle.com/javase/7/docs/api/java/awt/event/KeyEvent.html
Please do let me know if there are any errors or doubts :)

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.

What is causing my dice game to show an unrealistic amount of perfect rolls

I am trying to create a die rolling program. The goal is to roll a die until the chosen value comes up a certain number of consecutive times (I used the programmer defined name "rollLength" for this). I am trying to display how many total rolls it took until the die value comes up consecutively. The problem is when I run the program it shows that the rollLength came up perfectly with no wasted rolls which I know is unrealistic. My question is if you can suggest what is wrong with my code. I am not sure if I am doing nested loops wrong.
Here is my code.
package lab03_schultz;
import java.util.Scanner;
import java.util.Random;
public class Lab03_Schultz {
public static void main(String[] args) {
// WRITE main's CODE HERE
Scanner keyboard = new Scanner(System.in);
Random randomNumber = new Random();
//declare variables
int value, nSides, rollLength, roll;
int turns=0, n=0, count=0, totalThrows=0;
//ask for input
System.out.println("Please enter the number of sides (2, 4, or 6): ");
nSides = keyboard.nextInt();
System.out.println("Enter the value sought. Must be in the range [1," + nSides + "]: ");
value = keyboard.nextInt();
System.out.println("Enter the length of the run.\n" + "Remember, the bigger it is the longer it will take to find it");
rollLength = keyboard.nextInt();
System.out.println("Enter number of times to run the experiment:");
turns = keyboard.nextInt();
while(n!=value) {
roll = randomNumber.nextInt(nSides)+1;
n++;
}
while(count!=rollLength){ //countinue till count = rollLength
if(n==value){
count++; //count how many times n == value, this is to represent consective rolls for the value
} else if (n!=value) { //if n is not the value counter starts over at zero
count=0;
}
if (n!=value) {//This will count how many times the die didn't come up with the value
totalThrows++;
}
}
System.out.println("totalThrows: " + totalThrows); //finding what totalThrows is
//adds rolls (without watched value) and (when it showed watch value) together
System.out.println("Your total throws are: " + (totalThrows+rollLength));
}
}
This can be done with just a single loop
int rollsInARow = 0; // store how many times we roll the value
int totalThrows = 0;
while(rollsInARow != rollLength) {
int roll = randomNumber.nextInt(nSides)+1;
if(roll == value) {
rollsInARow++; // Count consecutive rolls that are the wanted value
} else {
rollsInARow = 0; // Reset if we get a roll other than value
}
totalThrows++; // +1 after each roll
}
We loop until we have the wanted rollLength. Each loop generates a random number and compares it to value. If they are equal, increment the counter. If different, reset the counter. At the end of each loop, keep track of total rolls.
Also a tip. When using an if statement to check a true/false value (n == value), you can simply use an else statement to catch the n != value because there are only two cases.
if(n == value) {
count++;
} else { // The same functionality as else if(n != value)
count = 0;
}
Your first while loop will run until n is equal to the value. It will not move past that block of code until n is equal to value.

Right Loop for this exercise in Java

Hi guys i am learning java in order to code in Android, i got some experience in PHP, so i got assigned an exercise but cant find the right loop for it, i tried else/if, while, still cant find it, this is the exercise:
1- prompt the user to enter number of students, it must be a number that can divide by 10 (number / 10) = 0
2- check of user input, if user input not dividable by 10 keep asking the user for input until he enter the right input
How i code it so far, the while loop not working any ideas how to improve it or make it work?
package whiledowhile;
import java.util.Scanner;
public class WhileDoWhile {
public static void main(String[] args) {
Scanner user_input = new Scanner(System.in);
/* int counter = 0;
int num;
while (counter <= 100) {
System.out.println("Enter number");
num = user_input.nextInt();
counter += num; // counter = counter + num
//counter ++ = counter =counter +1
}
System.out.println("Sum = "+ counter);
*/
int count = 0;
int num;
System.out.println("Please enter a number: ");
num = user_input.nextInt();
String ex;
do {
System.out.print("Wrong Number please enter again: " );
num++;
}
while(num/10 != 0 );
}
}
When using a while loop, you'll want to execute some code while a condition is true. This code needs to go inside the do or while block. For your example, a do-while loop seems more appropriate, since you want the code to execute at least one time. Also, you'll want to use the modulo operator, %, inside of your while condition, not /. See below:
Scanner s = new Scanner(System.in);
int userInput;
do {
// Do something
System.out.print("Enter a number: ");
userInput = s.nextInt();
} while(userInput % 10 != 0);
Two things:
I think you mean to use %, not /
You probably want to have your data entry inside of your while loop
while (num % 10 != 0) {
// request user input, update num
}
// do something with your divisible by 10 variable

Categories