在命令行上向args []添加变量

时间:2016-08-30 05:09:47

标签: java

我正在使用Head First的Java书籍学习Java,而且这段代码已经出现了。

import javax.sound.midi.*;


public class MiniMiniMusicCmdLine {   

 public static void main(String[] args) {
    MiniMiniMusicCmdLine mini = new MiniMiniMusicCmdLine();
    if (args.length < 2) {
        System.out.println("Don't forget the instrument and note args");
    } else {
        int instrument = Integer.parseInt(args[0]);
        int note = Integer.parseInt(args[1]);
        mini.play(instrument, note);

    }
 }

public void play(int instrument, int note) {

  try {

     Sequencer player = MidiSystem.getSequencer();         
     player.open();

     Sequence seq = new Sequence(Sequence.PPQ, 4);         
     Track track = seq.createTrack();  

     MidiEvent event = null;

     ShortMessage first = new ShortMessage();
     first.setMessage(192, 1, instrument, 0);
     MidiEvent changeInstrument = new MidiEvent(first, 1); 
     track.add(changeInstrument);


     ShortMessage a = new ShortMessage();
     a.setMessage(144, 1, note, 100);
     MidiEvent noteOn = new MidiEvent(a, 1); 
     track.add(noteOn);

     ShortMessage b = new ShortMessage();
     b.setMessage(128, 1, note, 100);
     MidiEvent noteOff = new MidiEvent(b, 16); 
     track.add(noteOff);
     player.setSequence(seq); 
     player.start();
     // new
     Thread.sleep(5000);
     player.close();
     System.exit(0);

  } catch (Exception ex) {ex.printStackTrace();}
  }
}

我试图在IntelliJ和命令行上运行它,但输出始终是相同的。该程序始终打印“不要忘记仪器和注意args”并自行执行。自从这本书出版以来,我是在做错事还是用Java改变了?

3 个答案:

答案 0 :(得分:0)

命令行

java MiniMiniMusicCmdLine 1 2

答案 1 :(得分:0)

要在命令行上将参数传递给args [],只需使用:

java MiniMiniMusicCmdLine ABCD PQRS

答案 2 :(得分:-1)

要在命令行中使用Command参数运行Java程序,您必须像往常一样编译,

<强> javac MiniMiniMusicCmdLine

并在命令行中传递参数

java file_name parameter1 parameter2 
  

java MiniMiniMusicCmdLine 1 2