【问题标题】:Trying to loop through an array within an array尝试遍历数组中的数组
【发布时间】:2018-05-08 05:28:23
【问题描述】:

我正在尝试打印我的 noteArray 的每个部分(例如:19,然后将“D”作为单独的部分)但是通过使用 For 循环,我得到了每行的一个含糊不清的打印消息。 “processNotes(noteArray)”方法是我希望输出的样子。

任何帮助将不胜感激!

public class question2 {
public static void main(String[] args) {
    Note[] noteArray = new Note[5];
    noteArray[0] = new Note(19, "D");
    noteArray[1] = new Note(10, "C");
    noteArray[2] = new Note(23, "F");
    noteArray[3] = new Note(20, "B");
    noteArray[4] = new Note(32, "C");
    processNotes(noteArray);
    for(Note i : noteArray){
        System.out.println(i);
        }
}
private static void playNote() {
    int numberDuration = Note.getduration();
    String letterPitch = Note.getpitch();
    System.out.println("The note "+ letterPitch +" is played for "+ 
numberDuration +" seconds.");
    return;
}
public static void processNotes(Note[] notes) {
    playNote();
}
}
class Note
{
private static String pitch;
private static int duration;
public Note(int duration, String pitch) {
    this.pitch = "C";
    this.duration = 10;
}
public static int getduration() {
    return duration;
}
public void setduration(int duration) {
    Note.duration = duration;
}
public static String getpitch() {
    return pitch;
}
public void setpitch(String pitch) {
    Note.pitch = pitch;
}
}

编辑:

我想要的输出: 音符 C 播放 10 秒。

我得到的数组输出:

Note@6d06d69c
Note@7852e922
Note@4e25154f
Note@70dea4e
Note@5c647e05

【问题讨论】:

  • 在 Note 类中覆盖 toString
  • 看看你在问题中得到了什么以及你想要什么会很有用。使用您的问题下方的编辑链接添加它。

标签: java arrays


【解决方案1】:

你有两种可能。

首先,重写您的 toString() 方法,以便在您 System.out.println() 时打印您想要的笔记。

其次,您可以在循环中,而不是打印注释:

for(Note i : noteArray){
    System.out.println(i.getPitch());
    System.out.println(i.getDuration());
}

【讨论】:

  • 绝对没问题,感谢您花时间解释!
【解决方案2】:

将以下内容添加到您的 Note 类中:

public String toString() {
    return "Duration = " + duration + ", pitch = " + pitch;
}

Demo


来自object.toString

返回对象的字符串表示形式。一般来说, toString 方法返回一个“以文本形式表示”的字符串 目的。结果应该是简洁但信息丰富的表示 这对一个人来说很容易阅读。建议所有 子类会覆盖此方法。

Object 类的 toString 方法返回一个字符串,该字符串由 对象是其实例的类的名称,at 符号 字符“@”和哈希的无符号十六进制表示 对象的代码。换句话说,这个方法返回一个字符串等于 为:

getClass().getName() + '@' + Integer.toHexString(hashCode())

您可以覆盖此方法以获得更有意义的输出。

建议进一步阅读:The connection between 'System.out.println()' and 'toString()' in Java

【讨论】:

  • 这正是我所追求的!但是,我如何通过在 Note 类的 noteArray 中循环来获取持续时间和音高并将其设置为多个不同的值?
  • 你可以使用setdurationsetpitch
  • 您能详细说明一下吗?我尝试在“setduration”部分添加一个循环,但我一直遇到问题。
  • @Tipzil 你需要从很多地方删除static 并修复Note 类的构造函数。见working demo here
【解决方案3】:

你可以重写 Note 类的 toString 方法,因为 sysout 隐式调用 toString。

【讨论】:

    猜你喜欢
    • 2019-02-16
    • 2013-09-23
    • 1970-01-01
    • 2014-09-09
    • 1970-01-01
    • 2010-12-14
    • 2013-11-03
    相关资源
    最近更新 更多