Increment int variable every 5 iterations of loop (JAVA) - java

i want to Increment int variable every 5 iterations of loop. so the current int is 009. I want to change it to an infinite loop wherein the value add + 1 every 5 loops. so after that the value of 009 will change to 010, then after 5 loops. again it will change into 011.
String itemID = "2014-009";
for (int i = 0; i <= 5; i++) {
String sdf = new SimpleDateFormat("yyyy").format(new java.util.Date());
String[] parts = itemID.split("-");
String part2 = parts[1];
int result = Integer.parseInt(part2);
String second = sdf + "-" + String.format("%03d", result + 1);
JOptionPane.showMessageDialog(null, second);
System.out.println(second);
}

Something like this should work:
int value = 0;
for (int i = 0; ; i++) {
if (i%5 == 0) {
value++;
}
}
Explanation:
The loop has no end, because it doesn't have a condition
The value variable is incremented only every 5 iterations
We enforce that restriction by asking whether i is exactly divided by 5
Be aware that I'm not taking into account the fact that ints are finite and at some point they will overflow. For truly "infinite" values (limited only by the memory available in your machine), we would have to use arbitrary precision values, BigInteger will come in handy for that.

Well, you should initialize result outside the loop.
Then you can do an infinite loop with a counter that checks if the iteration is divisable by 5 :
....
int result = Integer.parseInt(part2);
int i = 0;
while (true) {
i++;
if (i%5 == 0)
result++;
....
}

for(float i=0; i<10; i=i+0.2f){
System.out.println((int) i);
}
You can adapt the rest

In my case all above works on first iteration because 0%5 == 0 in my case is true and I suggest to write code like this:
if(i%5 == 0 && i != 0) {//6 threads per one operation
lq1.join();
lq2.join();
}

Related

How can i re-initialize the "i" variable of a loop in the body of the loop?

I'm creating a Java program to assign days in an array to days in a Year so I need to re-initialize my array after seven days basically. How can I re-initialize the "I" variable in my for-loop block.
public static void mainAction() {
for (int i = 0; i < day.numberOfDays; i++) {
if (day.dayNum == (i + 1))
day.day = DAYS[i];
if (dayNum == 7)
day.day = 1;
}
}
This code keeps on running
result = day.day%7
anytime day.day is greater than 7, It does a division and assigns the remainder to result.
% is the modulo operator

iteration through a loop

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.

Subtraction using while loop Java

So i'm trying to write a programme whereby the user enters two integers .
The programm is supposed to subtract 5 from the second integer entered in a loop depending on the first number entered. (so the first number should dictate how many times it will loop.
public int getScheme1() {
while (Mark >= 20) {
System.out.printf((Mark = Mark - 5) + Mark + " ");
}
for (int Day = 1; Day <= 20; Day++) {
System.out.printf("( " + Day + "):" + Mark + " ");
}
return Mark;
}
All my code does is print the user's second input integer 20 times.
Also im sorry im totally new to java
you must call this function in your main program.
public int getScheme1 (int num1, int num2){
for(int i = 1 ; i >= num1 ; i++ ){
num2 -= 5;
}
return num2;
}
to call it simply use getScheme1(num1,num2);
Based on what you described, you are looking for something like this:
Scanner input = new Scanner(System.in); //create a scanner to get user input
int a1 = input.nextInt(); //get 2 ints from the user
int a2 = input.nextInt();
for(int i = 0; i < a1; i++) { //loop as many times as a1 specifies
a2-=5; //subtract 5 from a2 each time it loops
}
System.out.println(a2);
The key part of this is the for loop, which works in the following:
for(variable; condition; increment),
basically, what the for loop I wrote is saying:
Set i = 0 at the start. If i is meeting the condition (in this case being less then a1), then loop. The increment part is called when it finishes running the code block, it now makes i bigger (in this case 1 bigger using ++) Another important thing to note is that the first time the loop runs, i = 0.
So for example, if I wanted to loop 10 times, with a starting variable of 3 and incremented 5 each time, I'd do:
for(int i = 3; i <= 53; i+=5) {}
Also, one last thing: please look at variable naming conventions, variables shouldn't start with caps like that, they should be camelCase

Algorithm output to length starts new line

I am trying to format the output from what I have written to display a list of primes (Eratosthenes) to a certain number results per line. Do they need to placed into an Array to accomplish this? I have not come across a way to implement their division besides .split("");, which would render a single line for each and the Oracle site's System.out.format(); argument index to specify length. Yet, these require the characters to be known. I am printing it with the following, which of course creates an infinite line.
for (int count = 2; count <= limit; count++) {
if (!match[count]) {
System.out.print(count + ", ");
}
}
Is there a way to simply call System.out.print("\n"); with an if(...>[10] condition when System.out.print() has run for instance 10 times? Perhaps I am overlooking something, relatively new to Java. Thanks in advance for any advice or input.
By using a tracker variable, you can keep track of how many items have been displayed already so you know when to insert a new line. In this case, I chose 10 items. The exact limit is flexible to your needs.
...
int num = 0;
//loop
for(int count = 2; count <= limit; count++)
{
if(!match[count])
{
if (num == 10) { System.out.print("\n"); num = 0; }//alternatively, System.out.println();
System.out.print(count + ",");
num++;
}
}
...
You can just simply create some int value e.g.
int i = 1;
...and increment it's value everytime Sysout is running.
Something like this:
int i = 1;
for (int count = 2; count <= limit; count++) {
if (!match[count]) {
if (i%10 == 0)
System.out.print(count+ "\n");
else
System.out.print(count + ", ");
i++;
}
}
Try this:
int idx=1;
int itemsOnEachLine=10;
for(int count = 2; count <= limit; count++)
{
if(!match[count])
{
System.out.print(count+(idx%itemsOnEachLine==0?"\n":","));
idx++;
}
}
you go increasing a counter (idx) along with every write, every 10 increments (idx modulus 10 == 0), you will be printing a new line character, else, a "," character.

Help with understanding java 'for' loops

I have to write a java program where the solution will include the printing of the arrow tip figure depending on the number of rows. Below are example of how the result should look. However, I cannot do this until I understand for loops. I know I have to work with the rows and columns and possibly nested loops. I just dont know how to connect the row with the columns using for loops. Please help me in understanding these loops. Thanks!
Example #1 (odd number of rows)
>
>>>
>>>>>
>>>>>>>
>>>>>
>>>
>
Example #2 (even number of rows)
>
>>>
>>>>>
>>>>>>>
>>>>>>>>>
>>>>>>>>>>>
>>>>>>>>>>>
>>>>>>>>>
>>>>>>>
>>>>>
>>>
>
a for loop will loop through a collection of data, such as an array. The classic for loop looks like this:
for(counter=0;counter <= iterations;counter++){ }
the first param is a counter variable. the second param expresses how long the loop should last, and the 3rd param expresses how much the counter should be incremented by after each pass.
if we want to loop from 1 - 10, we do the following:
for(counter=1;counter<=10;counter++){ System.out.println(counter); }
if we want to loop from 10 - 1, we do the following:
for(counter=10;counter>=1;counter--){ System.out.println(counter); }
if we want to loop through a 2 dimensional collection, like...
1 2 3
4 5 6
7 8 9
int[][] grid = new int[][] {{1,2,3},{4,5,6},{7,8,9}};
we need 2 loops. The outer loop will run through all the rows, and the inner loop will run through all the columns.
you are going to need 2 loops, one to iterate through the rows, one to iterate through the columns.
for(i=0;i<grid.length;i++){
//this will loop through all rows...
for(j=0;j<grid[i].length;j++){
//will go through all the columns in the first row, then all the cols in the 2nd row,etc
System.out.println('row ' + i + '-' + 'column' + j + ':' + grid[i][j]);
}
}
In the outer loop, we set a counter to 0 for the first parameter. for the second, to calculate how many times we will loop, we use the length of the array, which will be 3, and for the third param, we increment by one. we can use the counter, i, to reference where we are inside the loop.
We then determine the length of the specific row by using grid[i].length. This will calculate the length of each row as they are being looped through.
Please feel free to ask any questions you may have regarding for loops!
EDIT: understanding the question.....
You are going to have to do several things with your code. Here we will store the number of lines in a variable, speak up if you need to pass in this value to a method.
int lines = 10; //the number of lines
String carat = ">";
for(i=1;i<=lines;i++){
System.out.println(carat + "\n"); // last part for a newline
carat = carat + ">>";
}
The above will print out carats going all the way up. We print out the carat variable then we make the carat variable 2 carats longer.
.... the next thing to do is to implement something that will decide when to decrease the carats, or we can go up half of them and down the other half.
Edit 3:
Class Test {
public static void main(String[] args) {
int lines = 7;
int half = lines/2;
boolean even = false;
String carat = ">";
int i;
if(lines%2==0){even = true;} //if it is an even number, remainder will be 0
for(i=1;i<=lines;i++){
System.out.println(carat + "\n");
if(i==half && even){System.out.println(carat+"\n");} // print the line again if this is the middle number and the number of lines is even
if(((i>=half && even) || (i>=half+1)) && i!=lines){ // in english : if the number is even and equal to or over halfway, or if it is one more than halfway (for odd lined output), and this is not the last time through the loop, then lop 2 characters off the end of the string
carat = carat.substring(0,carat.length()-2);
}else{
carat = carat + ">>"; //otherwise, going up
}
}
}
}
Explanation and commentary along shortly. Apologies if this is over complicated (i'm pretty sure this is not even close to the best way to solve this problem).
Thinking about the problem, we have a hump that appears halfway for even numbers, and halfway rounded up for the odd numbers.
At the hump, if it is even, we have to repeat the string.
We have to then start taking off "<<" each time, since we are going down.
Please ask if you have questions.
I had the same question for a homework assignment and eventually came to a correct answer using a lot of nested if loops through a single for loop.
There is a lot of commenting throughout the code that you can follow along to explain the logic.
class ArrowTip {
public void printFigure(int n) { //The user will be asked to pass an integer that will determine the length of the ArrowTip
int half = n/2; //This integer will determine when the loop will "decrement" or "increment" the carats to String str to create the ArrowTip
String str = ">"; //The String to be printed that will ultimately create the ArrowTip
int endInd; //This integer will be used to create the new String str by creating an Ending Index(endInd) that will be subtracted by 2, deleting the 2 carats we will being adding in the top half of the ArrowTip
for(int i = 1; i <= n; i++) { //Print this length (rows)
System.out.print(str + "\n"); //The first carat to be printed, then any following carats.
if (n%2==0) { //If n is even, then these loops will continue to loop as long as i is less than n.
if(i <= half) { //This is for the top half of the ArrowTip. It will continue to add carats to the first carat
str = str + ">>"; //It will continue to add two carats to the string until i is greater than n.
}
endInd = str.length()-2; //To keep track of the End Index to create the substring that we want to create. Ultimately will determine how long the bottom of the ArrowTip to decrement and whether the next if statement will be called.
if((endInd >= 0) && (i >= half)){ //Now, decrement the str while j is greater than half
str = str.substring(0, endInd); //A new string will be created once i is greater than half. this method creates the bottom half of the ArrowTip
}
}
else { //If integer n is odd, this else statement will be called.
if(i < half+1) { //Since half is a double and the integer type takes the assumption of the one value, ignoring the decimal values, we need to make sure that the ArrowTip will stick to the figure we want by adding one. 3.5 -> 3 and we want 4 -> 3+1 = 4
str = str + ">>"; //So long as we are still in the top half of the ArrowTip, we will continue to add two carats to the String str that will later be printed.
}
endInd = str.length()-2; //Serves the same purpose as the above if-loop when n is even.
if((endInd >= 0) && (i > half)) { //This will create the bottom half of the ArrowTip by decrementing the carats.
str = str.substring(0, endInd); //This will be the new string that will be printed for the bottom half of the ArrowTip, which is being decremented by two carats each time.
}
}
}
}
}
Again, this was for a homework assignment. Happy coding.
Here is a simple answer for you hope it helps! Cheers Logan.
public class Loop {
public static void main(String[] args) {
for (int i = 0; i < 10; i++) {
int count = i;
int j = 0;
while (j != count) {
System.out.print(">");
j++;
}
System.out.println();
}
for (int i = 10; i > 0; i--) {
int count = i;
int j = 0;
while (j != count) {
System.out.print(">");
j++;
}
System.out.println();
}
}
}
For making a 'for' loop:
public class Int {
public static void main(String[] args) {
for (Long num = 1000000L; num >= 9; num++) {
System.out.print("Number: " + num + " ");
}
}
}
Output:
Number: 1008304 Number: 1008305 Number: 1008306 Number: 1008307 ...

Categories

Resources