In this method I am asked to print out an Array that has 100 integers in it. It is supposed to be printed out in 10 rows of 10. However, a row will randomly break onto the next line, leaving 2 partial lines. Any clues at to what might be causing this? Thanks.
You can use mod (%) operation, like below,
for(int i = 0; i < myGrades.length; i++) {
if(i % 11 == 0) {
System.out.println("");
} else {
System.out.print(myGrades[i] + " ");
}
}
You can try this code instead:
for (int i = 0; i < myGrades.length; i++) {
System.out.print(myGrades[i] + " ");
if (i % 10 == 9) {
System.out.println();
}
}
But it looks like your code functions correctly. This is most likely an issue with console output. Also, it is conventional to start variables at 0 not 1, which would mean using line < 10.
I'm trying to print following pattern:
0
11
0
222
0
3333
0
222
0
11
0
I want to achieve this by using recursion and a loop inside said recursive method, which gets one integer value passed. The int value determines how far this pyramid pattern goes. In the example above the int value would be 3.
I managed to get the bottom half, but I have no idea to get the upper half.
if (arg != 0) {
System.out.println("0");
for (int i = 0; i <= arg; i++) {
System.out.print(arg);
}
System.out.println();
print(arg - 1);
}
How would I be able to somehow implement some increment, which turns to a decrement to this recursion? Since I'm thinking this would be how I could achieve the above pattern.
Thank you very much in advance!
You can pass two arguments. The Max value and start value which will be zero and
then increment start value until reaches max
then decrement Max until reaches zero
call--> printline(3);
private static void printline(int input, int... vars) {
if (input == 0) {
System.out.println(0);
return;
}
int start= vars.length > 0 ? vars[0] : 0;
start++;
System.out.println("0");
for (int i = 0; (i <= start && i <= input); i++) {
System.out.print(start >= input ? input : start);
}
System.out.println();
if (start >= input) {
input--;
}
printline(input, start);
}
}
I hope someone can help. My problem is with using the modulus operator in a for loop. My code is as follows:
for (int i = 0; i < 10; i++)
if (i % 2 == 0) {
method1();
}
else {
method2();
}
I understand how this loop works in that it iterates between if and else because of the even and odd numbers created by the condition that uses
the modulus operator (i % 2 == 0)
However, I want to create a condition using the modulus operator so that my loop iterates through 4 methods - as in:
loop starts{
method1();
method2();
method3();
method4();
loop repeats
}
I can't work out how to accomplish this. I would appreciate any help and advice.
Thanks in advance.
Put j = i % 4
And check for method1() j should be equal to j = 0, similarly for
Method2() check j = 1. And so on. Put for range conditions to 1 for infinite loop or desired range.
You could be looking to use the switch statement. More on that here.
Basically it takes a variable to switch between cases.
For example:
for(int i = 0; i < 10; i++){
switch(i%2) {
case 0: method0();
break;
case 1: method1();
break;
}
}
Here is the out put if method0 printed 0, and method1 printed 1:
1
0
1
0
1
0
1
0
1
0
You can edit the modulus to whatever number you want, you just have to account for the different possibilities.
Do you mean something like this?
for(int i = 0; i < 10; i++)
{
if(i%4 == 0)
{
condition
}
else if(i%4 == 1)
{
condition
}
else if(i%4 == 2)
{
condition
}
else if(i%4 == 3)
{
condition
}
}
Remember to put it on paper if you're confused and loop through your head (as a beginner)
I am working on an exercise where a small piece of code based on a for-loop is converted to preform the same operation with a while loop. The conversion is wrong by purpose, and looks like this:
int sum = 0;
for (int i = 0; i < 4; i++) {
if (i % 3 == 0) continue;
sum += i;
}
System.out.println(sum); // prints 3
This is converted into:
int i = 0, sum = 0;
while (i < 4) {
if (i % 3 == 0) continue;
sum += i;
i++;
}
System.out.println(sum); // will not print
In the exercise, I am asked to explain why the conversion is wrong and then fix it. My thoughts are:
With the initial value of i = 0, this will trigger continue instantly after entering the will loop, since (0 % 3 == 0) will make the if-statement true. As long as the initial value is 0, this will execute the loop, for so to skip it an endless amount of times. I tried changing the initial value of i = 1, but noe sum is printed. Then I tried to increment i before executing the if-statement, and the program now prints the sum 7. The question here is; why won't the program print if i incremented after the if statement, even if the initial value of i = 1 suggests (in my head) that program should run properly?
I made a table for each program to compare the summing.
The for-loop version:
i = 0, sum += i not preformed (continue), i++
i = 1, sum = 1, i++
i = 2, sum = 3, i++
i = 3, sum += i not preformed (continue), i++
i = 4, i < 4 false, loop stopped
The while-loop version:
i = 0, i++, sum = 1
i = 1, i++, sum = 3
i = 2, i++, sum += i not preformed (continue)
i = 3, i++, sum = 7
i = 4, i < 4 false, loop stopped
In the while-loop, sum += i is preformed once more than in the for-loop. Is this the right way to convert the for-loop into a while-loop?
int i = 0, sum = 0;
while (i < 3) {
i++;
if (i % 3 == 0) continue;
sum += i;
}
System.out.println(sum);
Your 1 is focussing on it being the initial value, but that's not the point. The point is that i is never incremented when i % 3 == 0 is true, not that 0 is the initial value. So the while loop loops forever.
Your 2 doesn't make any sense: The while version will loop forever, never summing anything.
Is this the right way to convert the for-loop into a while-loop?
No, you're incrementing i at the wrong time.
Think bout how a for loop works:
Initialization - First it sets the variables to the values in the first expression.
Test - Then it tests the values using the second expression.
Execute - If the value is true, it executes the loop body.
Increment - When the loop body is complete, it executes the third (increment) expression. Note that this is after the loop body.
Make your while loop do what the for loop is doing. (I'm intentionally not doing that for you; this is a learning exercise. I'll note that the best way to convert that for loop will not use continue, however. "Best," of course, is subjective.)
In the exercise, I am asked to explain why the conversion is wrong and then fix it
The conversion is wrong simply because when you will reach a i value that modulo 3 equals 0 (the first iteration in that case), you will skip to the next iteration and re-validate. However, since you skipped directly without incrementing i , you will re-validate the same condition and re-validate ad-infinitum.
You could fix it easily by getting rid of the continue and negating the condition :
while (i < 4) {
if (i % 3 != 0)
sum += i;
i++;
}
The for-loop given by the question if converted to plain English, it means sum up from 0 to 3 and exclude all multiples of 3. (0+1+2=3)
for (int i = 0; i < 4; i++) {
if (i % 3 == 0) continue;
sum += i;
}
So now, we ask ourselves, how do we sum up 0 to x and exclude all multiples of 3 using a while-loop. We will do this without looking at the original for-loop. (Sometimes it is easier to do it this way since we already know the intention of the for-loop)
To sum up a number from 0 to 3:
int i = 0;
while(i < 4){
sum += i;
i++;
}
To sum a number from 0 to 3, excluding multiples of 3:
int i = 0;
while(i < 4){
if(i % 3 != 0)
sum += i;
i++;
}
To sum a number from 0 to 3, excluding multiples of 3 (using continue):
int i = 0;
while(i < 4){
if(i % 3 == 0){
i++; //Remember to increase i before continue
continue;
}
else
sum += i;
i++;
}
Since after the continue, all statements below it will be skipped, you have to remember to do an increment i++ before calling continue. There will be another i++ since you branch out into 2 conditions now.
According to the while loop logic, increment of variable i is conditional where as for for-loop it is unconditional. To make the increment logic uniform, you should increment in both cases.
I think the proper converting would be -
int i = 0, sum = 0;
while (i < 4) {
if (i % 3 == 0) {i++;continue;}
sum += i;
i++;
}
System.out.println(sum);
Normally the increment would be on the last line of a while loop. However, in this "disaster waiting to happen" code, there is a condition to skip to the end of the while block without incrementing i. If you are relying on i to increment, make sure it is always executed on any iteration. And also, at the end, because you want it to iterate the first time.
while (i < 4) {
if (i % 3 == 0) {
// skip!
} else {
sum += i;
}
i++;
}
I have a for loop that checks for every 5th position. And at every 5th position, I'm performing an action like so (which works):
for(int i = 0; i < foo().length; i++)
{
System.out.print(i);
if(i == 5 || i == 10 || i == 15)
System.out.println();
}
Is there a way to write if statement so no matter how long foo().length is, I don't have to keep coming back to adjust it?
Use modulus(%) operator: -
if (i % 5 == 0) {
}
5 % 5 == 0, 10 % 5 == 0, ...
Since you are using a for loop, you can simply change your increment from i++ to i += 5, and leave the if condition.
for (int i = 0; i < someNum; i += 5) {
// No need to check for `i` against `modulus 5`.
}
You can use next for witout if statement
for(int i = 0; i < foo().length; i+=5)
{
adding 5 to i step by step
Use the following:
if ( i % 5 == 0 )
if you want to put it in a single print statement this would work too.
for(int i = 0; i < foo().length; i++)
{
System.out.printf("%d%s", i, (i%5==0) ? "\n" : "");
}