This article describes the use of for loops in Java to solve the classic chicken and rabbit cage problem. Share it for your reference, as follows:
For loop classic, chicken and rabbit cage problem
Question: There are 35 chickens and rabbits in the same cage. There are 94 legs in the cage. How many chickens and rabbits are there?
Idea: First, clarify the idea. The number of chickens *2 plus the number of rabbits *4 is equal to the total number of feet 94. This is a key point.
The code is very simple, but it takes a lot of time to find the key conditions. If you don't understand it, it's really annoying.
Use the for loop to list all possible until if the condition is met.
List the expression chicken*2 plus rabbit*4 equals the total number of feet 94. This is the judgment condition of if. If, you can directly output the number of chickens and rabbits if it is satisfied.
package demo;public class LoopDemo4 { public static void main(String[] args) { // There are 35 chickens and rabbits in total, and there are 94 legs in the cage. Find out how many chickens and how many rabbits there are respectively // The number of chickens*2 plus the number of rabbits*4 is equal to 94. // Use the for loop to list all possible until if the condition is met. int sum = 35; int foot = 94; // Because there will be no odd number of feet, int type for (int chook = 1; chook <= foot / 2; chook++)// Assumed number of chickens { int rabbit = sum - chook; // Assumed number of rabbits if (rabbit * 4 + chook * 2 == foot)// When it is established, it is the correct number of chickens and rabbits, and it outputs directly and ends the loop { System.out.println("The number of chickens is: " + chook); System.out.println("The number of rabbits is: " + rabbit); break; } } }}Running results:
For more information about Java algorithms, readers who are interested in this site can view the topics: "Java Data Structure and Algorithm Tutorial", "Summary of Java Operation DOM Node Tips", "Summary of Java File and Directory Operation Tips" and "Summary of Java Cache Operation Tips"
I hope this article will be helpful to everyone's Java programming.