I was wondering what would be a real difference between setting up code like this
public boolean stringE(String str) {
int count = 0;
for (int i =0; i < str.length(); i++) {
if (str.charAt(i) == 'e') {
count += 1;
}
}
return (count >=1 && count<=3 );
}
and this
public boolean stringE(String str) {
for (int i =0; i < str.length(); i++) {
int count = 0;
if (str.charAt(i) == 'e') {
count += 1;
}
}
return (count >=1 && count<=3 );
}
I know the first one is right but what would make it difference by setting "int count =0" inside "for loop". Wouldn't it still add 1 to the count =0 ?
The second case won't compile, since count won't be recognized in the return statement, since the scope of the count variable is only inside the for loop in that case.
That's why you have to declare count outside the for loop.
Another problem with the second case, as mentioned by Dici, is that you reset count to 0 in each iteration of the loop, which means the loop wouldn't count what it is supposed to count.
In second case, the variable count is not visible outside for loop so that will create error at return statement. Also the logic is wrong since it will get reset everytime.
You can always try - and in this case, you might notice that the second one won't compile. It's syntactically incorrect.
In Java, when you define a variable, it only exists in the scope of the braces {} it's defined in. If you define a variable inside a loop, it only exists inside the loop. You can't use count outside the braces it's defined in.
Also, I doubt even the first program is semantically correct - you always return during the first iteration, which is unlikely to be what you want.
Related
I have to write a method that returns/prints the odd numbers between 1 and 100, but I have to use another method, which checks whether a given integer is odd or not:
static boolean isOdd(int c) {
boolean d;
d = c % 2 != 0;
return d;
}
I'm guessing that I have to use either a for- or while-loop (probably can be done with both?), but I think what I'm really struggling with is "connecting" both methods. So the numbers actually run through isOdd() which determines whether they are odd.
I've tried these two options so far, but they're not working.
Option 1:
static void func1() {
int number = 1;
while (number < 100 && isOdd(number)) {
System.out.println(number);
number = number + 1;
}
}
Option 2:
static void func1() {
int i;
for (i = 1; i < 100; i++) {
isOdd(i);
}
System.out.println(i);
}
Your attempt #1 is closer to your goal ;)
you are right that you can use while and for (and probably other kinds of processing multiple numbers, but that just for the sake of completeness, forget it for now)
your println (or print) should be within the loop because you want to print more than just one number.
in you current attempt #1 you end your loop with the first odd number: 1 This doesn't count up very far ;)
So you have to use an if inside your loop where you check the result of isOdd(number) and only print if it's odd.
But the loop has only the upper bound limit as condition (number < 100) as you want to check all the numbers.
Smartass hint (try it only after your program works fine): if you count up by 2 instead by 1 (number = number + 2;), your program will only need half the time - and you could even skip the isOdd check ;-)
I'm guessing that I have to use either a for- or while-loop (probably can be done with both?)
Yes. for-loops are just syntactic sugar for special while-loops:
for (init_stmt; cond; incr_stmt) body_stmt;
is equivalent to
init_stmt;
while (cond) {
body_stmt;
incr_stmt;
}
Let's first write this using a for-loop.
for-loop
for (int i = 1; i < 100; i++)
if (isOdd(i))
System.out.println(i)
Note that we can (and should!) do the declaration of i as int in the for-loop initializer.
Now, we may translate this to an equivalent while-loop:
while-loop
int i = 1;
while (i < 100) {
if (isOdd(i))
System.out.println(i);
i++;
}
Mistakes in your attempts
Attempt 1
You've mistakenly included the check in the condition (rather than using it in an if inside the loop body); the first even number (2) will cause the loop to terminate.
Attempt 2
You're not even using the return value of isOdd here. You're unconditionally printing i after the loop has terminated, which will always be 100.
The ideal implementation
Ideally, you'd not be filtering the numbers; you'd directly be incrementing by 2 to get to the next number. The following loop does the job:
for (int i = 1; i < 100; i += 2)
System.out.println(i);
Is it possible to have two loops in a function?
public static void reduce(Rational fraction){
int divisorNum = 0;
int n = 2;
while(n < fraction.num){
if(fraction.num % n == 0){
divisorNum = n;
System.out.println("n: " + divisorNum);
n++;
}
}
int divisorDenom = 1;
int m = 2;
while(m<fraction.denom){
if(fraction.denom % m == 0){
divisorDenom = m;
System.out.println("m: " + divisorDenom);
m++;
}
}
}
I'm trying to get the greatest common denominator. I know this is the very long way about doing this problem but I just wanted to try having two loops. When I call this function, only the first loop gets printed and not the second. I originally had an if statement, but seeing that the second loop doesn't execute I figured that I fix this part first.
Here's my other part of the code:
public static void main(String[] args){
Rational fraction = new Rational();
fraction.num = 36;
fraction.denom = 20;
reduce(fraction);
}
Absolutely. There are no limitations
Watch your conditional test = is not quite ==
Based on your edit I suspect fraction.denom is initialized at 1 or 0
Hence you will never get in the second loop
You can have any number of loops in your function :-
1.You can have nested loops;
2.Two loops side by side.
SO,your piece of code is fine enough considering the value of n, until the conditions for loop execution are met :-
public static void ....
while(n<x){
do this
add to counter
}
while(m<x){
do this
add to counter
}
if(y==z){ // NOTE :- Here you have committed mistake, compare using ==, not by =(it will be always true else and your condition will always be met else)
print this
}
Yup. You even can have 3 if you try hard enough.
EDIT: The didactic version:
Loops, as the name suggest, are constructs that allow you to repeat blocks of code several times (post conditional loops -> until certain condition is met keep running, pre conditional loops -> if certain condition is met, keep running). This is often called "iteration". So in a typical for-loop:
for ( int i = 0; i < 10; ++i )
print(array[i]);
You can say you're "iterating" over the array 10 times.
This has nothing to do with functions. You can have several loops inside a function, or functions being called inside loops. As long as you define your "blocks" of code (with begining and ending braces) you do what you think its best.
Yes, there are no limitations when it comes to looping. You could do 1000 while loops if you wanted.
An example here could be doing something like making a square out of *...
Here's an example
for(int i = 0; i < 4; i++)
{
for(int j = 0; j < 4; j++)
{
System.out.print("*");
}
System.out.println();
}
It would look like:
****
****
****
****
So I had this while loop for a lab in my class I had to make. I then had to convert the loop to a do-while loop to see the difference in design and make sure I got the same results. Now I need to convert it into a for loop, but I don't know how to set up the for statement. Here is how it is currently:
do
{
die1Value = generator.nextInt(6) + 1;
die2Value = generator.nextInt(6) + 1;
if (die1Value == die2Value)
{
if (die1Value == 1)
{
snakeEyes += 1;
}
else if (die1Value == 2)
{
twos += 1;
}
else if (die1Value == 3)
{
threes += 1;
}
else if (die1Value == 4)
{
fours += 1;
}
else if (die1Value == 5)
{
fives += 1;
}
else if (die1Value == 6)
{
sixes += 1;
}
}
count += 1;
}while (count < NUMBER);
As others have mentioned, the problem arises that the for loop will check the condition at the beginning of the loop, but your do while loop will check the condition at the end of your loop.
All that means is that with a for loop, you are not guaranteed at least one iteration. However, with a do while loop, you are guaranteed at least one.
Assuming that's not a problem, the for loop statement could be this:
for (count = 0; count < NUMBER; count++)
count = 0 may need to be changed to count = 1 or whatever count is originally supposed to start at.
However, seeing as how count would need to be initialized for your current code, you can just omit the initialization part in your for loop like so:
for (; count < NUMBER; count++)
Make use of the Java Tutorials and Java Docs; you look to have a grip on the syntax and the meaning of each part of the loop so it shouldn't be too hard to figure out how to convert it once you read this.
(source)http://docs.oracle.com/javase/tutorial/java/nutsandbolts/for.html
The for statement provides a compact way to iterate over a range of values. Programmers often refer to it as the "for loop" because of the way in which it repeatedly loops until a particular condition is satisfied. The general form of the for statement can be expressed as follows:
for (initialization; termination; increment) {
statement(s);
}
When using this version of the for statement, keep in mind that:
The initialization expression initializes the loop; it's executed once, as the loop begins.
When the termination expression evaluates to false, the loop terminates.
The increment expression is invoked after each iteration through the loop; it is perfectly acceptable for this expression to increment or decrement a value.
The do-while loop does not check the condition on the first iteration, but a for loop does. Therefore, you need to make condition in for loop always true at the first time.
Try this:
for (boolean keepWorking = true; keepWorking; keepWorking = ++count < NUMBER) {
// ...
}
This may seem silly, but I'm a bit confused about the following code:
public class Loops{
public static void main(String[] args) {
int i = 0;
int j = 2;
int k = 0;
boolean continue = i<j;
while (continue && k < 2) {
i++;
j--;
k++;
}
System.out.println(j);
}
}
This program prints 0, but I just don't understand why it doesn't print 1. The way I see it, after one loop i = j = 1. And thus continue = false. So if anyone can explain to me the logic behind this I would greatly appreciate it!
continue does not reevaluate itself after every loop iteration because he is defined outside of the loop.
instead, check in the loop condition for i < j
while (i<j && k < 2) {
i++;
j--;
k++;
}
Your loop would be optimized by compiler as:
boolean continue = i<j;
while (true && k < 2)
and finally
while (k < 2)
So it need to loop two times to exit
After the first loop: j == 1, k == 1
After the second loop: j == 0, k == 2, exit now
this is why finally j == 0
Try out putting condition inside a while():
while (i<j && k < 2)
Continue is only set outside of loop body, it is never updated during the loop. Thus continue is set to true before the loop starts and then never modified again.
First of all, your continue variable always evaluates to true (0 < 2) so we can ignore it.
First iteration:
i ends up evaluating to 1.
j ends up evaluating to 1.
k ends up evaluating to 1.
As k < 2, we do another iteration.
Second iteration:
i ends up evaluating to 2.
j ends up evaluating to 0.
k ends up evaluating to 2.
As k == 2, we exit the loop.
Then we print j, which evaluates to 0.
You only set the value of variable 'k' once and consequently continue as well. You need to re-evaluate the conditional expression inside the loop as well.
That said, I would suggest you refrain from using 'continue' as a varible name; I'm fairly certain it is a reserved word in many languages.
So I've been practicing my Java programming skills on the CodingBat website, when I came across this problem. In it, you have to make a simple method that takes in an array of integers of dynamic length, check to see if the elements in the array are in increasing order (1, 2, 3, 15678, etc), and return "true" if true, or "false" if there is an integer out of order.
Firstly, I initialize a boolean variable named "result". Then, I iterate through the array of integers passed by the method. If the current index value is less than the next index value, I set "result" to "true", and repeat the loop. Else, I'll set "result" to "false", break out of the loop and set "result" to "false". After the FOR loop, I return "result".
However, I've been receiving an error message that "result" has not been initialized properly. I can kinda understand the confusing with the JVM, however I thought that setting the value for "result" inside of the IF/ELSE statements would solve that.
Here is a copy of the code that I have done so far:
public boolean scoresIncreasing(int[] scores) {
boolean result;
for (int i = 0; i < scores.length; i++) {
if (i < (i + 1)) {
result = true;
}
else {
result = false;
break;
}
}
return result;
}
First of all, i < i+1 will always be true, unless i = Integer.maxValue, in which case you'll wrap around to Integer.minValue.
What you want is scores[i] < scores[i+1] , and you'll need to adjust your loop values to avoid an index out of bounds on the last iteration.
So, your code fixed:
public boolean scoresIncreasing(int[] scores) {
boolean result;
for (int i = 0; i < scores.length-1; i++) // fix loop end
{
if (scores[i] < scores[(i + 1)]) {
result = true;
}
else {
result = false;
break;
}
} // missing brace
return result;
}
Try this as an alternative. It works on the principle that once you get a false, you can get out immediately.
public boolean scoresIncreasing(int[] scores) {
boolean result = true; // assume true
for (int i = 0; i < scores.length-1; i++) // fix loop end
{
if (scores[i] > scores[(i + 1)]) return false;
} // missing brace
return result;
}
Of course, you may want to introduce bounds checking at the beginning to ensure that there are at least two values.
You are simply missing a closing brace (}) before return result.
As a suggestion to simplify the code (and deal with arrays of 0 elements!), you may want to initialize result to true. Then, as you loop over the array, change result to false if and only if you find an element out of order.
One other word of caution. You use element i + 1 in your for loop. Think about what will happen when you get the last element in the array (i == scores.length - 1).
if (i < (i + 1)) will always evaluate to true. You need to compare the contents of the array at those indexes, not the indexes themselves.
Something like:
public boolean scoresIncreasing(int[] scores) {
for(int i = 0; i < scores.length-1; i++) {
if(scores[i] > scores[i+1]) return false;
}
return true;
}
What if scores has 0 elements? ;]
in your code, you are returning result inside the for loop (after the if-else statement).
Add another bracket before the return statement (to close the for loop)