数组内的变量未在 Java 中更新其值

问题描述

我正在尝试解决 FizzBu​​zz 问题,并决定使用一个数组将前 15 个结果存储在数组中,然后对其进行迭代。但是如果在循环中稍后更新,则存储在数组中的变量不会更新其值

import java.util.Scanner;

 public class FizzBuzz {

    public static void main(String[] args) {
    // Todo Auto-generated method stub
    Scanner sc= new Scanner(system.in);
    System.out.println("Enter the number"); 
    int Num= sc.nextInt();
    String F= "Fizz";
    String B= "Buzz";
    String FB= "FizzBuzz";
    String I="";
    String arr[]= {FB,I,F,B,I};
    for (int j = 1; j <= Num; j++) {
        I = Integer.toString(j);
        System.out.println(arr[j%15]);
    }
  }
}

变量 I 在 for 循环中不会改变它的值。它只是在 I 变量的结果中打印空格。帮助!

P.S:对于天真的解决方案,这是一个很好的实现吗?

解决方法

变量不更新的原因如下: 如果你创建一个局部变量,比如这里的 String I = ...,并将它传递给一个数组,它将作为变量的实例存储在那里。如果您更改字符串(或字符串的值),则实例会更改。所以一个字符串被认为是一个实例。如果您创建一个新字符串,则会自动创建一个新实例 - (String s =) new String(...) 相当于更改变量 s = "..."。您可以为字符串编写一个包装器,其中字符串值是“可变的”,即可变的,而无需更改数组中传递的实际实例。
您还可以更改代码,而无需包装器:

    public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    System.out.println("Enter the number");
    int num = sc.nextInt();
    String f = "Fizz";
    String b = "Buzz";
    String fb = "FizzBuzz";
    String i = "";
    String[] arr = {fb,i,f,b,i};
    for (int j = 1; j <= num; j++) {
        int index = j % 15;

        //local constant to check for equality to the i-variable
        final String pos = arr[index];

        String strToInt = Integer.toString(j);
        
        //Check for equality to the "i"-variable
        if (pos.equals(i)) {
            arr[index] = strToInt;
        }

        //Changing the i-instance to the strToInt instance
        i = strToInt;
        
        //Printing your result
        System.out.println(arr[index]);
    }
}

我还将变量名称更改为有效名称,如 JNC(Java 命名约定)所述。

您真诚的,
文森特

,
import java.util.Scanner;

public class Main {

    public static void main(String[] args) {

        Scanner sc = new Scanner(System.in);
        System.out.println("Enter the number");
        int num = sc.nextInt();
        String f = "Fizz";
        String b = "Buzz";
        String fb = "FizzBuzz";
        String i = "";
        String[] arr = {fb,i};

        String indexValue;
        for (int j = 1; j <= num; j++) {
            indexValue = arr[j % 15];
            System.out.println(indexValue.equals(i) ? j : indexValue);
        }
    }
}