如何在处理过程中进行 if 语句验证?

How do I make an if statement validation in processing?

我几个小时以来一直在努力解决这个问题,但我似乎找不到 solution.The 代码基本上是一个约会程序,当它运行时会弹出一个框,然后 'secretary' 插入患者的姓名和时间。但是,如果我将 "Maria" 设置为“1200”并再次将 "John" 设置为“1200”,系统将立即用 John 替换 Maria。我的代码如下:

String[] names = new String[2400];  // from 0:00 until 24:00

void setup()
{
  String name = "";
  do
  {
    name = input("Name");
    if (name.equals("ABORT")) { 
      System.exit(0);
    }  // end the program
    int time = int(input("Time code (e.g. 840 or 1200)"));
    names[time] = name;
    showAllNames();
  }
  while (true);   // loop never ends

}

void showAllNames()     // shows all the times where there is a name
{
  for (int t = 0; t < 2400; t=t+1)
  {
    String name = names[t];
    if (name!=null)
    {
      println(t + "\t" + name);
    }
  }  
  println("================");
}

public String input(String prompt)
{ 
  return javax.swing.JOptionPane.showInputDialog(null, prompt);
}

如何添加 if 命令以在写入之前检查位置是否为空 - 否则会警告用户?

在写入之前检查索引是否为 null:

if(names[time] == null){
    //Add the name
} else {
    //If the name isn't null, perhaps go to the next index, or throw an exception
}

如果名字是null,你想做什么完全取决于你。

我也想补充几点建议:

  • 将您的名称设为 ArrayList 变量,这样您就可以添加任意数量的名称而无需更改变量。

  • 不要在循环中调用 showAllNames() 方法,而是在循环结束后调用它。

  • 使用普通索引而不是时间索引,这样您就不必进行空检查。