java - 在其他类中实现对象参数

标签 java

我希望有人可以帮助我解决这两个让我陷入项目困境的值(value)观。我有两个类,第一个类生成一个具有随机值的二维数组。

import java.util.concurrent.ThreadLocalRandom;

public class Guitar {

private int strings;
private int chords;

public Guitar(int mstrings, int mchords) {
    this.strings = mstrings;
    this.chords = mchords;
}

private double[][] song = new double[strings][chords];

public void generateSong() {
    for (int i = 0; i < song.length; i++) {
        for (int j = 0; j < song[i].length; j++) {
            song[i][j] = ThreadLocalRandom.current().nextDouble(27.5, 4186);
            System.out.printf(" %.2f",song[i][j]);
        }
        System.out.println();
    }
}

}

行数和列数由命令行参数确定。 args[0] 是行数,args[1] 是列数。我在主方法类中将它们转换为 int 变量

public class Songwriter {

public static void main(String[] args) {

    System.out.println("Guitar(): Generated new guitar with " + args[0] + " strings. Song length is " + args[1] + " chords.");

    String args0 = args[0];
    int strings = Integer.parseInt(args0);
    String args1 = args[1];
    int chords = Integer.parseInt(args1);

    Guitar guitarObj1 = new Guitar(strings, chords);
    guitarObj1.generateSong();

}

}

我的问题在于传递命令行参数的 int 变量以使二维数组具有相应的大小。我知道我的代码并不是完全错误的,当我将字符串和和弦变量设置为 3 和 4 或 Guitar 类本身中的任何值时,表格打印得很好。

抱歉,如果我看起来一无所知。我的类(class)刚刚涵盖了面向对象编程的第一章,但我还没有掌握基础知识。

最佳答案

这是有问题的行:
private double[][] Song = new double[字符串][和弦];

当您创建 Guitar 类的新对象时,song 数组将使用 stringschords 的值进行初始化那个时候,(很可能)是 0。

将其更改为:

private double[][] song;

public Guitar(int mstrings, int mchords) {
    this.strings = mstrings;
    this.chords = mchords;

    song = new double[mstrings][mchords];
}

编辑:OP,你刚刚回答了你自己的问题:)

It doesn't crash but the only output is the system.out.print in the first line of the main. I believe it's because the strings and chords variables default to 0, making the array 0x0, and I'm failing to change their values

关于java - 在其他类中实现对象参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36417084/

相关文章:

java - 有没有办法在手机上查找java内存状态?

java - AWS cloudwatch 用于实时监控应用程序

java - 使用 AsyncTask 成功更新 RecyclerView,但 Activity/UI 线程中的 Arraylist 大小未更改

java - 有没有办法根据Java中字符串中有多少个字母来创建相同字符的char数组?

java - 在运行时从 XSD 创建 Java 类

JavaFX:如何创建带有通知徽章的应用程序图标?

java - 切换到 Gradle 后无法在 NetBeans 中执行调试任务

c# - 使用java程序控制网络浏览器

java - 如何从 Java IntStream 中的嵌套 .forEach 收集结果

Java - 使用反射获取对静态类的引用