开发者

Ask for yes/no to go back to the loop

How do i go back to the try loop if the user answers Y/y? I know the code below doesn't ask for the user's Do you want to try again (Y/N)?. I can only use bufferedReader at the moment.

import java.io.*;

public class Num10 {
    public static void main(String[] args){
        String in="";
        int start=0, end=0, step=0;

        BufferedReader input = new BufferedReader(new InputStreamReader(System.in));


        try{
            System.out.print("Input START value = ");
            in=input.readLine();
            start=Integer.parseInt(in);
            System.out.print("Input END value = ");
            in=input.readLine();
            end=Integer.parseInt(in);
            System.out.print("Input STEP value = ");
            in=input.readLine();
            step=Integer.parseInt(in);
        }catch(IOException e){
            System.out.println("Error!");
        }

        if(start>=end){
            System.out.println("The starting number should be lesser than the ending number");
            System.exit(0);
        }else
        if(step<=0){
            System.out.println("The step number should always be greater than zero.");
            System.exit(0);
 开发者_如何学运维       }

        for(start=start;start<=end;start=start+step){
            System.out.println(start);
        }       

        System.out.println("\nDo you want to try again (Y/N)?");
    }
}


A do ... while loop would be appropriate for this.

boolean again = false;
do
{
     // your code here
     again = askQuestion();
} while(again);

or you could just use a regular while loop:

boolean again = true;
while(again)
{
    // your code here
    again = askQuestion();
}

And for both of these, askQuestion is another method that asks the user a question and returns true or false.


use do{..... }while();

like:

boolean again=true;
do{
    try{
    //your code
    }
    //your code
}while(again);

How do i go back to the try loop if the user answers Y/y?
You can not go back to try{.....} . You must use

public static void main(String... args){
    //your code
} 

instead of public static void main(String[] args){}
and to go back use main(); at your desired location of code.


How do i go back to the try loop if the user answers Y/y?

try doesn't create a loop. That's the problem.

Loops "go back" automatically until something happens to end the loop. That's what makes them loops.

So you put an actual loop around the try block, and ask the question at the end of the loop, and break out of the loop if it is answered with N/n (or whatever; you can decide for yourself how you want to handle it if the input is some other garbage). The do - while loop is appropriate because it checks for its exit condition at the end, rather than the beginning (like while and for).


Java has a lot of tools for something like this. These are known as "loops". The loops available in Java are the while, do ... while, for, and for ... each. The while loop is the simplest. It looks like this:

while (condition) {
    // Some code
}

Basically, where I put "condition" you put any boolean value. A boolean value is simply a value that can be either true or false, nothing else. In Java, you can create variables of the boolean type, but often times, you won't explicitly create a boolean.

Instead, you'll use conditional statements. For example x < y, x == y, and x >= y are all "conditional statements". That means, in the end, they evaluate into a boolean value. So, in this code:

int x = 1;
int y = 5;
if (x < y) {
    // Code
}

Where it says x < y, it's actually evaluating it into true behind the scenes. Boolean values are important, and are used in many places in Java.

Anyway, back on the topic of loops, let's get to the next loop, do ... while. It looks like this:

do {
    // Code
} while (condition);

do ... while works the same as while, but it always runs at least once, even if the condition is false.

for and for ... each are slightly more complicated. They are really just shortcuts. Consider the following code:

int i = 0;
while (i < 10) {
    System.out.println("I is: " + i);
    i++;
}

Here, the loop will run 10 times, and i will keep track of how many loops. The for loop can do the same thing, but in a more concise way:

for (int i = 0; i < 10; i++) {
    System.out.println("I is: " + i);
}

That code will do the same thing the first one did, but it uses a for loop. As you can see, the for loop has three parts. In the first, you can declare a variable, in the second, you put a condition, and in the third, you put something that's run every iteration of the loop. for loops are often used when iterating over arrays, but you may not have learned that yet, so don't fret.

The for ... each loop is more complicated than all the others, so if you don't understand it just yet, don't worry. Basically, it's a fast way to get all the elements of a list, or anything that's in the Collections API. For example, say you have a list of Strings, you could use this to get all the Strings in the list:

for (String string : aList) {
    System.out.println(string);
}

That would go through every String in the list and print it out.

Anyway, back to the problem at hand. Here, we need to chose a loop to use, and it seems that the best one for the situation would be a simple while loop. Just do something like this:

boolean condition = true;
while (condition) {

    // Your code

    try {
        while (true) { //Creates an infinite loop
            in = input.readLine();
            if (in.equalsIgnoreCase("y")) {
                condition = true;
                break;
            } else if (in.equalsIgnoreCase("n")) {
                condition = false;
                break;
            } else {
                System.out.println("Please enter either Y or N.");
            }
        }
    } catch (IOException e) {
        System.out.println("ERROR!");
    }

}

Here, we use two while loops. The first wraps the entire code, checking for a boolean called condition. We've initialized it to be true, so the loops will always run at least once. Second, I made another while loop. Here, I did while (true), which will run forever. However, you can "break" out of a loop by using the break keyword. The reason I used this, is the user has a possibility of entering something other than "y" or "n". In that case, it should just ask them again. If it gets "Y", it sets condition to true and breaks out of the loop (which is technically unnecessary, since condition is already set to true). If it gets "N" it sets it to false and breaks out of the loop. Since it is now false, the loop will be exited and the program will end.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜