【问题标题】:Accessing a variable from inside a do-while loop [closed]从do-while循环内部访问变量[关闭]
【发布时间】:2013-05-14 01:43:44
【问题描述】:

如何在 Java 的 do-while 循环中访问变量?

下面的代码写出一个值,直到输入的值不在 0 到 10 之间。

这是我的代码:

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

只要输入介于 0 和 10 之间,循环就会继续请求输入。一旦输入其他数字,循环就会终止并显示所有输入数字的总和。

【问题讨论】:

  • 你的问题不清楚。
  • 你想做什么? 在哪里你试图访问变量?
  • 除了下面的答案,你可能是指(a&gt;=0 &amp;&amp; a&lt;=10)

标签: java variables while-loop scope do-while


【解决方案1】:

try like(在循环外声明变量a):

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

【讨论】:

  • 感谢您的回答,但您为什么要初始化 int a = -1 而不是 int a = 0
  • 它也可以是 0,但为了安全起见,您正在检查 > 0 但稍后也可能包含 0,但包含负数的机会要少得多
  • 有趣的概念......肯定会记住......它可能会时不时地节省几行......我从没想过!
  • @vishal_aim - 嗨。请不要在没有看到更改的情况下批准 suggested edits
  • 你根本不需要初始化它。
【解决方案2】:

要访问循环之外的变量,您需要在循环外声明/初始化它,然后在循环内更改它。如果有问题的变量不是 int,我建议您将其初始化为 null。但是,由于您无法将 int 变量初始化为 null,因此您必须将其初始化为某个随机值:

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
    }
}

注意:如果您只是在循环之前声明变量而不初始化它(根据@Evginy 的回答),您将能够在循环外访问它,但您的编译器会抱怨它可能尚未初始化。

【讨论】:

  • 非常感谢您的回答!
【解决方案3】:

试试这个

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

【讨论】:

  • 感谢您的回答。但是,我确实想将Scanner in = new Scanner(System.in); 保留在循环内吗?我真的不在乎它在循环之外
猜你喜欢
  • 1970-01-01
  • 2013-03-13
  • 1970-01-01
  • 2016-01-24
  • 1970-01-01
  • 1970-01-01
  • 2015-04-24
  • 2018-01-16
  • 2010-09-18
相关资源
最近更新 更多