【问题标题】:Initializing variables in For Loops (Java)在 For 循环 (Java) 中初始化变量
【发布时间】:2018-10-02 23:14:13
【问题描述】:

我需要创建一个程序,从用户那里接收 4 个整数,并确保输入是否在 0 到 255 之间。一切正常,除了我的最终输出,IP 地址几乎是一个字符串中的所有输入。它一直打印出 0,因为我必须在将变量用于数组之前对其进行初始化,因此我为它们分配了 0 的值。但是,该值应该在 for 循环中更改,但它仍然打印出不正确的值。我只能打印一次 IP 地址,而且必须在最后。我知道有一种更简单的方法可以做到这一点,但我仍然想知道如何解决这个问题以供将来参考。以下是我的代码:

导入 java.util.Scanner;

类主{

public static void main(String[] args) {
    Scanner run = new Scanner(System.in);
    String per = ".";
    int firstInput = 0;
    int secondInput = 0;
    int thirdInput = 0;
    int fourthInput = 0;
    boolean firstMeetsParameters = true;
    boolean secondMeetsParameters = true;
    boolean thirdMeetsParameters = true;
    boolean fourthMeetsParameters = true;
    int[] inputs = new int[] {firstInput,secondInput,thirdInput,fourthInput};
    boolean[] condition = new boolean[] {firstMeetsParameters,secondMeetsParameters,thirdMeetsParameters,fourthMeetsParameters};
    String[] num = new String[] {"first", "second", "third", "fourth"};
    for(int x = 0; x < inputs.length; x++) {
        System.out.println("Please enter the " + num[x] + " octet:");
        inputs[x] = run.nextInt();
        if(inputs[x] < 0 || inputs[x] > 255) {
            condition[x] = false;
        }
    }
    for(int i = 0; i < inputs.length; i++){
        if(condition[i] == false) {
            System.out.println("Octet " + (i+1) + " is incorrect.");
        }        
    }
    System.out.println("IP Address: " + firstInput + per + secondInput + per + thirdInput + per + fourthInput);    
}

}

【问题讨论】:

  • 您只是在更改 inputs 数组中的值。您永远不会更改 firstInputsecondInput 等的值。当您执行new int[] { firstInput, ... }; 时,您正在将值复制到新数组中。数组值没有引用变量。

标签: java for-loop variables initialization


【解决方案1】:

运行此代码并获得启发:

int x = 0;
int[] a = new int[] {x};
x = 1;
System.out.println(a[0]); // What do you think.. does this print 0 or 1?
a[0] = 2;
System.out.println(x); // What do you think.. does this print 1 or 2?

一旦你理解了 new int[] {x};不会将 x 和数组 a 的第一个插槽“链接”在一起,而 new int[] {x};上面与 new int[] {0} 没有什么不同,您应该能够弄清楚它为什么不起作用:您将用户输入分配到 inputs[] 数组的 4 个插槽中,而您从未接触过firstInput 变量,直到您打印它,此时它显然仍然是您创建它时的样子:0。

【讨论】:

    【解决方案2】:

    您永远不会设置 firstInput、secondInput 等的值。

    如果您将输出语句更改为以下内容,它将起作用。

    System.out.println("IP Address: " + inputs[0] + per + inputs[1] + per + inputs[2] + per + inputs[3]);
    

    【讨论】:

      【解决方案3】:

      问题出在变量引用上。您正在输入数组中设置值,但打印变量 firstInput, secondInput... 因为它们是本机类型,所以它们之间没有引用。您应该像这样使用输入数组进行打印:

      System.out.println("IP Address: " + inputs[0] + per + inputs[1] + per + inputs[2] + per + inputs[3]);
      

      inputs[0] 上设置的值不会改变 firstInput 变量上的值。

      【讨论】:

        猜你喜欢
        • 2011-04-02
        • 2012-01-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-03-08
        • 1970-01-01
        相关资源
        最近更新 更多