Accessing a variable from inside a do-while loop [closed]

青春壹個敷衍的年華 提交于 2019-11-28 13:56:52

问题


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.


回答1:


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);



回答2:


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.




回答3:


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");


来源:https://stackoverflow.com/questions/16533859/accessing-a-variable-from-inside-a-do-while-loop

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!