Basically, I want the if and else statements at the bottom to happen again when my counter reaches 13. How do I do it? My code is below.
int counter = 2;
int start = 19;
int end = 95;
while(!(input>=start && input<=end) /*range*/ && counter<100){
start+=95;
end+=95;
if(counter % 4 == 0)
end+=19;
else if(counter % 5 == 0)
start+=19;
counter++;
}
EDIT:
Sorry for being unclear. Uhh, what I want to do is, if the if-else statements have already been executed 13 times, I want the whole thing, including the
start+=95;
end+=95;
to execute again.
wrap the codes in the loop into a method. when executes every 13 times, invoke the method again
int innerLoop=(counter==13)?2:1;
for (int i=0; i<innerLoop; i++) {
...
}
Related
This is what i have:
int count = 0;
do {
if(number % 10 == 2){
count++;
}
number = number /10;
} while (number > 0);
return count;
It works fine but is there a way to write it without using the do loop? I have an assignment that doesn't allow it
I'm new at java so let me know if you need me to clarify something let me know
There are hundreds of ways to approach this. The while code looks pretty similar to your do-while:
int count = 0;
while(number > 0) {
if (number % 10 == 2) count++;
number /= 10;
}
return count;
String replace is a cute tactic (though perhaps not efficient):
// total length - length without 2s = length of 2s
String numStr = String.valueOf(num);
int count = numStr.length() - numStr.replace("2", "").length()
Elliot's version is even sexier:
// Replace all "not 2s" and count length
int count = String.valueOf(num).replaceAll("[^2]", "").length();
What you are using is a 'do-while' loop which is an exit control loop and I'm glad you are trying to learn how to convert between loops.
The most useful and efficient loop for this code is going to be the 'while' loop since the 'for' loop is usually used for iterations in which we know the end goal or number of interations on the whole.
public int method(int number){
int count = 0;
while(number > 0) {
if (number % 10 == 2) {
count++;
}
number = number / 10;
}
return count;
}
The above example is for your code to be converted to the 'while' loop. The basic code is the same however the java statement in the 'do' bloc become the part of the 'while' bloc.
It is not recommended to use the 'for' loop here since it is going to complicate the process unneccsarily however for the sake of curiosity this is the code.
public int method(int number){
int count;
for(count = 0; number > 0 ; count++){
if((number % 10) != 2){
count--;
}
number = number / 10;
}
return count;
}
The above code is one way of executing the 'for' loop. Note that in the 'for' loop the count increases without any condition hence, in the loop we have added a count-- to prevent the unintended increment in the count variable.
I have used something called 'shorthand operators' which can make statements like number = number / 10 smaller like this, number /= 10.
Do let me know if you find anything complicated and keep experimenting. It's rare to find the questions like these which are conceptual and technically basic but I am glad this community is vast.
Let me know about any further queries, I had a lot of fun answering this!
It would be something like this:
while(number > 0) {
if(number % 10 == 2) {
count++;
}
number /= 10;
}
The only difference is that a while loop will only run if its condition is met, while a do-while loop will run at least once.
try this:
public class Sample{
static int count = 0;
public static void main(String []args){
System.out.println(Sample.Count(50));
}
public static int Count(int number){
if(number>0){
if(number%10==2){
count++;
}
number = number/10;
Count(number);
}
return count;
}
}
Lets assume n=20
so after every 6 iterations I will do some processing
int i=0
for (t=6;t<20;t=t+6){
while(i<=t){
will do some processing
i++;
}
}
In the above code it will terminate when t=18, but I want to continue until 20.
How to do that ?
You are increasing the t variable 6 units... the last condition that satisfies the t<20 is when t = 18.
instead of doing t+=6 do a normal t++ and play with the modulo %6
example:
public static void main(String[] args) {
int n = 20;
for (int i = 0; i < n; i++) {
//TODDY
insert your while in here depending on when that must be executed
if (i % 6 == 0) {
System.out.println("am on a 6 modulo step..." + i);
} else {
System.out.println("foo#" + i);
}
}
System.out.println("done");
}
The behaviour is correct only.. Still if you want to perform any operation, do it after the condition is met, try below snippet:
int i = 0, n = 20;
do{
i += 6;
System.out.println(i);
} while (i < n);
System.out.println(i);
your code is not doing something every 6th iteration, but instead you are doing (n - n%6) times. your "will do some processing" is inside the while. If you add a print (or debug) there you will notice it; on the n=20 example the while will be executed 18 times; it will do something 18 times.
if you want to execute every 6th iterations, and include one extra for the cases that are not exactly divisible by 6, then you could do:
if (n == 0) {
return;
}
int number_iterations = n/6 + (n%6!=0 ? 1:0);
for (int i=0; i<number_iterations; i++) {
// do something
}
That covers what you requested; if not, pls edit question to be more clear on your exact needs.
So I started learning Java only a few days ago and I'm doing really well except for this one exercise that boggles my mind. So the exercise is to "Write a program which displays all numbers from 1 to 30 indivisible by 3". So this is easy:
class numbers {
public static void main (String args[]) {
for (int i = 0; i <=30; i++){
switch(i % 3){
case 0 :
break;
default :
System.out.println(i);
break;
}
}
}
}
Except one of the variants says "use break after divisibility by 3 is detected. Now I'm not sure if hte break used in the code above is correct, as it is a part of switch. I was wondering if there was an other way to do it.
Some fixes:
class names should start with Upper letter, name class Numbers, not numbers
start iterating from 1, not from 0, because you are displaying numbers in range [1..30].
Because here you have only 2 possibilities (is or is not indivisible), replace switch with if statement. Switch is more suited for a large range of conditions.
Most important. Using break will make you get out of the loop. Using continue will skip this loop and go to next iteration.
So now your code should look shorted and cleaner:)
class Numbers {
public static void main (String args[]) {
for (int i = 1; i <=30; i++){
if(i % 3 == 0){
continue;
}
System.out.println(i);
}
}
}
}
Or you could go with shorter version:
for (int i = 1; i <=30; i++){
if(i % 3 != 0){
System.out.println(i);
}
}
Another short solution.
As we know that from 1 to 30 there are only 10 numbers divisible by 3, we make ten loops to print them all.
for (int i = 1; i <= 30; ++i) {
System.out.printf("%d%n%d%n", i++, i++);
}
The idea is to print the two numbers before the one which is divisible by 3 and skip the one which is divisible.
the counter i starts at 1
the first %din System.out.printf prints current i (i=1) and increase it by 1 (i=2)
the second %din System.out.printf prints current i (i=2) and increase it by 1 (i=3)
the end condition of the for-loop increase i by 1 (i=4)
repeat till the end condition i <= 30 is false
edit A more readable version (as proposed by ajb)
for (int i = 1; i <= 30; i += 3) {
System.out.printf("%d%n%d%n", i, i + 1);
}
The code is OK - if i % 3 results in 0, nothing is printed. Since there are only two possiblities I would rewrite as if-statement:
if( ( i % 3 ) != 0 )
{
System.out.println( i );
}
Is in my opinion better readable and conveys the intent more clearly.
More on the actual statement:
switch( i % 3 )
{
case 0:
//do nothing
break; // leave switch - statement
...
}
The break is needed to leave the switch statement. So yes, it is necessary.
I want to loop infinitely using a for loop if a number equals 0, and loop until that number number if the number is greater than 0. Here's the code to help visual what I'm getting at.
for (int i = 0; i < this.getNumRounds(); i++) {
// 30 some lines of code
}
or
for ( ; ; ) {
// 30 some lines of code
}
if getNumRounds() is greater than 0, do the first loop, if it equals 0, do the second. I would prefer to do this without copying and pasting my 30 some lines of code twice and using an if statement seeing as the code is redundant, though I could use a function to take out that redundancy, but I'm looking to see if there's another option.
Use the powerful ternary operator:
for (int i = 0; this.getNumRounds() == 0 ? true : i < this.getNumRounds(); i++) {
// 30 some lines of code
}
As noted in the comments by yshavit, there is a shorter, cleaner way of expressing this:
for (int i = 0; this.getNumRounds() == 0 || i < this.getNumRounds(); i++) {
// 30 some lines of code
}
Have you thought about using a while loop instead?
int i = 0;
while(i < this.getNumRounds() || this.getNumRounds() == 0) {
//some 30 lines code
i++
}
So you want something like this:
int num = //whatever your number equals
if (num == 0) {
boolean running = true;
while (running) {
doLoop();
}
} else {
for (int i = 0; i < num; i++) {
doLoop();
}
}
private void doLoop() {
//some 30 lines of code
}
This code puts the contents of the loop in a separate method and checks if the number is equal to 0. If it is, the program runs the doLoop() method forever. Otherwise, it runs until i equals the number.
While it would be better to just create a method and use an if-statement you could add an if statement inside the for-loop to decrease i every iteration. It would look like:
for (int i = 0; i <= this.getNumRounds(); i++) {
if(this.getNumRounds() == 0){
i--;
}
// 30 some lines of code
}
Notice I changed i < this.getNumRounds() to i <= this.getNumRounds. This way if the number of rounds is zero then the loop will be called.
You could do the following.
for (int i = 0; i < this.getNumRounds() || i == 0; ++i) {
do {
// 30 lines of code
} while (this.getNumRounds() == 0);
}
If getNumRounds is non-trivial to compute, consider pulling it out of the loop and calling it only once.
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) {
// ...
}