Java while до исключения

while loop | do while loop Java Explained [Easy Examples]

Loops in Java are used. when we need to repeatedly execute a block of statements. The two most important types of loops are the while loop and the for loop. while loop in Java is a control flow statement that allows code to be executed repeatedly based on a given Boolean condition. The while loop can be thought of as a repeating if statement.

In this tutorial, we will learn about while loop java in detail. We will cover different examples and various kinds of while loop java including an empty and infinite while loop. At the same time, we will also discuss the use of break and continue statements in the while loop and their role in control flow. Moreover, we will also the nested while loops and how they actually work by taking different examples.

Towards the end, we will also give a touch to the java do-while loop and will solve examples. All in all, this is going to be a full tutorial about while loop java, and we are sure that by the end of this tutorial you will have a deep understanding of while loop.

Getting started with while loop in Java

while loop in Java may contain a single, compound, or empty statement. The loop repeats while the test expression or condition evaluates to true. When the expression becomes false, the program control passes to the line just after the end of the loop-body code. Here is a simple diagram that explains the while loop java pictorially.

while loop , do while loop Java Explained [Easy Examples]

In the following section, we will learn the basic syntax of while loop java along with some examples.

Syntax of while loop in Java

The syntax of while loop java is very simple. We need to write the condition inside the brackets as shown below:

Now let us take a simple example and print all the numbers from 0 up to 5. See the example below.

number. 0 number. 1 number. 2 number. 3 number. 4

Notice that once the condition inside the while loop becomes false, the program stops executing the while loop.

Syntax and example of empty while loop in Java

An empty while loop java does not contain any statement in its body. It just contains a null statement which is denoted by a semicolon after the while statement: The simple syntax looks like this;

Notice that there is nothing inside the body of the while loop except a semi-colon. Now let us take an example of the empty while loop. See the example below:

Notice that we increment the num inside the condition which is fine. The above empty loop will be executed until the condition becomes false. Because it is an empty while loop java, it will not return anything when we run the code. Such a loop is a time delay loop. The time delay loop is useful for pausing the program for some time. For instance, if an important message flashes on the screen and before we can read it, it goes off. So, In such cases, we can use a time delay loop to get sufficient time to read the message.

Syntax and example of Java infinite loop

A while loop can be an infinite loop if we skip writing the update statement inside its body or the condition is always true. The following is the simple syntax of the java infinite loop;

Читайте также:  Python list types in module

It is important that to have always a true condition for an infinite loop, otherwise, the loop will stop, once the condition becomes false. Now let us take an example of java infinite while loop. See the example below;

Notice that the above condition is always true as we are not updating or incrementing the number inside the loop. If we run the above code, it will iterate or execute the while loop infinitely time. We can stop an infinite loop by pressing ctrl+ C button on the keyboard.

Iterating an array using while loop in Java

Now we know the basics and important concepts about the while loop. Let us now iterate over an array using while loop java and print out all the elements. See the example below:

// class public class Main < public static void main(String[] args)< // array of int type int arr[]=; //INDEX starts with 0 as array index starts with 0 too int INDEX=0; // while loop java: while(INDEX <5)< // printing the element System.out.println(arr[INDEX]); // updating the index INDEX++; >> >

The break statement in the Java loop

The break keyword is a command that works inside Java while (and for) loops. When the break command is met, the Java Virtual Machine breaks out of the while loop, even if the loop condition is still true. No more iterations of the while loop are executed once a break command is met. This is useful when we want to stop the loop when a certain condition meets. See the example below, which stops the loop even the initial condition is true all the time.

// class public class Main < public static void main(String[] args)< // variable int num = 0; // while loop java: while(true)< // if condition if(num==7)< break; >System.out.println("counting. "+num); num++; > > >
counting. 0 counting. 1 counting. 2 counting. 3 counting. 4 counting. 5 counting. 6

Notice that even the initial condition was true all the time but still we managed to come out of the while loop using a break statement.

While loop in Java with continue statement

Java continue command is also used inside Java while (and for ) loops. The continue command is placed inside the body of the while loop. When the continue command is met, the Java Virtual Machine jumps to the next iteration of the loop without executing more of the while loop body. The next iteration of the while loop body will proceed like any other.

If that iteration also meets the continue command, that iteration too will skip to the next iteration, and so forth. Now let us take an example and say that we want to print the numbers from 0 to 9 without printing the number 5. In such cases, we can use the continue statement. See the example below;

// class public class Main < public static void main(String[] args)< // variable int num = 0; // while loop java: while(num<10)< // if condition if(num==5)< num++; // continue statement continue; >// printing the num System.out.println("counting. "+num); num++; > > >
counting. 0 counting. 1 counting. 2 counting. 3 counting. 4 counting. 6 counting. 7 counting. 8 counting. 9

Notice that we were able to print the numbers without printing number 5. We used the continue statement which skips the number 5 and prints others.

Nested while loop in Java

When a while loop exists inside the body of another while loop, it is known as nested while loop in java. Initially, the outer loop executes once and the afterward inner loop begins to execute. Execution of the inner loop continues until the condition of the inner loop is satisfied(until the test expression is false). In this section, we will have a look at the java nested while loops and will solve examples as well.

Читайте также:  На java вычислить логарифм

Syntax and example of Java nested while loop

As we already discussed nested while loop is when one while loop is inside another while loop. The simple syntax of nested while loop looks like this:

// Outer while loop while(condition1) < // inner while loop while(condition2)< // statements >>

We can put as many while loops inside each other as we wanted. Now, let us take an example of java nested while loop. See the example below:

// class public class Main < public static void main(String[] args)< // variable int num = 1; // while loop in Java: while(num<5)< // printing the table System.out.println("Table of "+num); int num2 = 1; // inner while loop while(num2< 6)< // printing the table System.out.print(num*num2+" "); num2++; >// printing new line System.out.println(""); // updating the num num++; > > >
Table of 1 1 2 3 4 5 Table of 2 2 4 6 8 10 Table of 3 3 6 9 12 15 Table of 4 4 8 12 16 20 

Notice that we were successfully able to print the table of numbers from 1 to 5 using nested while loop. There can be many other cases as well where nested loops help us to solve the problem easily.

do-while loop Java

Unlike the for and while loops, the do-while loop is an exit-controlled loop which means a do-while loop evaluates its test-expression or test-condition at the bottom of the loop after executing the statements in the loop-body. Even if the condition is false, the loop is going to be executed at least once. In this section, we will have a look at the syntax of the java do-while loop and will solve examples using the do-while loop.

Syntax of do-while loop in Java

In the for and while loops, the condition is evaluated before executing the loop-body. The loop body never executes if the test expression evaluates to false for the first time itself. But in some situations, we want the loop-body to execute at least once, no matter what is the initial state of the test expression. In such cases, the do-while loop is the best option which is executed at least once even the condition is always false. The simple syntax looks like this:

First, the statements inside the do will be executed and then the program will check the condition in the while loop. If the condition is false, the loop will not execute for the second time but if the condition is true the do statements will again execute.

Examples of do-while loop in Java

Now we already know the syntax of the Java do-while loop. Let us now take an example and see how it actually works. See the example below:

// class public class Main < public static void main(String[] args)< // do while loop do< System.out.println("Do while loop"); >while(false); > >

Notice that even the condition was false, the do-while loop was executed once. Now let us take another example and print the numbers from 1 to 5 using do-while loop;

// class public class Main < public static void main(String[] args)< // variable int num =0; // do while loop do< num++; System.out.println("counting. "+num); >while(num <5); >>

Источник

‘while’ statement cannot complete without throwing an exception — Android

‘while’ statement cannot complete without throwing an exception. Reports for, while, or do statements which can only exit by throwing an exception. While such statements may be correct, they are often a symptom of coding errors.

I hate warnings and I want to fix it. How can i fix this warning, or there is a better solution for this infinite loop.

you have an infinite loop ( while(true) ) and the only way to exit this loop is via exception. find another way to exit your while-loop, e.g. via a flag

A boolean check that you then change within the lifecycle of the application would also suffice as pointed out by Blackbelt.

Is this a compiler warning, or is it a «warning» of the kind that Android Studio likes to litter the codebase with? By default, Android Studio will try to make numerous suggestions about alternative ways to write your code.

4 Answers 4

This warning is a false positive; you should ignore it.

Usually, an infinite loop is a sign of a mistake somewhere; in your code, an infinite loop is exactly what you want.

You are probably using Android Studio or IntelliJ.

If so, you can add this above your method containing the infinite loop to suppress warnings:

@SuppressWarnings("InfiniteLoopStatement") 

Or add this «magic» comment above the statement:

//noinspection InfiniteLoopStatement 

This will tell the IDE that this is ok.

More generally, when you get a false positive warning, do Alt+Enter and do what showed on the screenshot below (select class only if your class is full of false positive, for the same warning)

comment wont take effect without a space after «//». also, in my case what helped was // noinspection InfiniteLoopJS

You probably got this warning using IntelliJ IDEA, right?

As the others already mentioned, this warning can usually be ignored.

If you want to disable it, open Settings and go to Editor > Inspections and search for Infinite loop statement . Simply uncheck the box and you’re done.

And in general, you can simply place your text cursor over a warning you wish to disable and press Alt + Enter, then click on the inspection info field and click Disable inspection.

If you want something to fire every second you can follow this methodology where you are sure that it will remove the callback later when you leave. This calls itself every second until you are done with the activity. You could even remove the callbacks earlier if you want in the lifecycle such as within onPause() or onStop() if so desired.

Handler handler = new Handler(); @Override protected void onCreate(Bundle savedInstanceState) < super.onCreate(savedInstanceState); handler.post(updateTime); >@Override protected void onDestroy() < super.onDestroy(); handler.removeCallbacks(updateTime); >private final Runnable updateTime = new Runnable() < public void run() < try < // Updating time every second long diffInHours = Methodes.diffInHours(endTime, diffInDays); long diffInMinutes = Methodes.diffInMinutes(endTime, diffInDays, diffInHours); long diffInSeconds = Methodes.diffInSeconds(endTime, diffInDays, diffInHours, diffInMinutes); tvTime2.setText(addZeroInFront(diffInHours) + ":" + addZeroInFront(diffInMinutes) + ":" + addZeroInFront(diffInSeconds)); handler.postDelayed(this, 1000); >catch (Exception e) < e.printStackTrace(); >> private String addZeroInFront(long diffInHours) < String s = "" + diffInHours; if (s.length() == 1) < String temp = s; s = "0" + temp; >return s; > >; 

Hot Network Questions

Subscribe to RSS

To subscribe to this RSS feed, copy and paste this URL into your RSS reader.

Site design / logo © 2023 Stack Exchange Inc; user contributions licensed under CC BY-SA . rev 2023.7.21.43541

By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.

Источник

Как сделать реализацию модели возобновления исключения?

Исключение отлавливается в блоке try<> далее выбирается подходящий catch()<> и управление передается именно туда. Когда исключение обработано , то есть закончилось выполнение блока catch()<> , выполняется блок finally<> , если он имеется конечно.

2 ответа 2

Цикл while, который выполняется до тех пор, пока исключение не перестанет выдаваться:

while(true) < try < //код, выбрасывающий исключение break; >catch(IOException e) < //Тут обрабатываем исключение, если надо. >> 

То есть если было выброшено исключение, то оно будет обработано в блоке catch(), а затем продолжится цикл. А если исключение не было выброшено, то цикл прервется на строке break .

Вот пример рекурсивного вызова метода в результате выкинутого исключения.Пример в связи с использованием рекурсии не очень корректный но принцип реализации я думаю ясен:

public boolean example(int x) < boolean result = true; int step = x; try < for (int i = x; i < 10; ++i) < step = i; if (i < 6) < throw new Exception(); >else < System.out.println(result); result = false; break; >> > catch (Exception e) < System.out.println("Exception"); result = this.example(++step); >return result; > 

вот еще один пример.В данном случае логика опирается на изменение флага:

public void example() < boolean flag = true; do < for (int i = 0; i < 10; ++i) < try < if (i < 6) < throw new Exception(); >else < flag = false; >> catch (Exception e) < >> > while (flag); > 

Источник

Оцените статью