【发布时间】: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数组中的值。您永远不会更改firstInput、secondInput等的值。当您执行new int[] { firstInput, ... };时,您正在将值复制到新数组中。数组值没有引用变量。
标签: java for-loop variables initialization