Accessing a variable from inside a do-while loop [

2020-02-16 05:23发布

How can I access a variable from inside a do-while loop in Java?

The code below writes out a value until the value entered is not is between 0 and 10.

Here is my code :

import java.util.Scanner;

public class DoWhileRange {
    public static void main(String[] args) {
        do{
            System.out.println("Enter a number between 0 an 10");
            Scanner in = new Scanner(System.in);
            int a = in.nextInt();
                int total +=0;
        }while (a>0 && a<10);

        System.out.println("Loop Terminated");
        System.out.println("The total is : "+total);
    }
}

The loop continues to ask for input so long as the input is between 0 and 10. Once some other number is entered the loop terminates and displays the total of all inputted numbers.

3条回答
【Aperson】
2楼-- · 2020-02-16 06:16

try like (declare the variable a outside the loop):

    int a = -1;
    do{
        System.out.println("Enter a number between 0 an 10");
        Scanner in = new Scanner(System.in);
        a = in.nextInt();
    }while (a>0 && a<10);
查看更多
疯言疯语
3楼-- · 2020-02-16 06:22

try this

    Scanner in = new Scanner(System.in);
    int a;
    do {
        System.out.println("Enter a number between 0 an 10");
        a = in.nextInt();
    } while (a > 0 && a < 10);
    System.out.println("Loop Terminated");
查看更多
Anthone
4楼-- · 2020-02-16 06:23

To access a variable beyond the loop, you need to declare/initialize it outside of the loop and then change it inside the loop. If the variable in question wasn't an int, I would suggest that you initialize it to null. However, since you can't initialize an int variable to null, you'll have to initialize it to some random value:

import java.util.Scanner;

public class DoWhileRange {
    public static void main(String[] args) {
       int a = 0; //create it here
        do {
            System.out.println("Enter a number between 0 an 10");
            Scanner in = new Scanner(System.in);
            a = in.nextInt();
        } while (a>0 && a<10);
        System.out.println("Loop Terminated");
        // do something with a
    }
}

NOTE: If you simply declare the variable before the loop without initializing it (as per @Evginy's answer), you'll be able to access it outside the loop but your compiler will complain that it might not have been initialized.

查看更多
登录 后发表回答